python:多線程+隊列Queue 實現:生產者和消費者demo__python

來源:互聯網
上載者:User
# -*- coding: UTF-8 -*-# __author__ = 'Sengo'import Queueimport threadingimport timeclass BookThread(threading.Thread):    def __init__(self, thread_id, q, func):        threading.Thread.__init__(self)        self.threadID = thread_id        self.q = q        self.func = func    def run(self):        print "線程 %d 開啟" % self.threadID        # TODO        process_book(self.threadID, self.q, self.func)        print "線程 %d 結束" % self.threadIDdef process_book(thread_id, q, func):    global existFlag    while not existFlag:        queueLock.acquire()        if not q.empty():            book = q.get()            queueLock.release()            # TODO deal_book            print "Thread %d processing book %s" % (thread_id, book)            func(book)            time.sleep(1)        else:            queueLock.release()queueLock = threading.Lock()existFlag = 0def start_book_threads(book_list, func):    global existFlag    existFlag = 0    thread_list = []    book_queue = Queue.Queue()    # 建立多線程    for threadID in range(1, THREAD_NUM + 1):        thread = BookThread(threadID, book_queue, func)        thread.start()        thread_list.append(thread)    # 填充隊列    queueLock.acquire()    for book in book_list:        book_queue.put(book)    queueLock.release()    # 等待隊列清空    while not book_queue.empty():        pass    # 通知線程是時候退出    existFlag = 1    print "book_queue is empty"    # 等待所有線程完成    for t in thread_list:        t.join()    print "Exist Main Book Thread"def deal_book(bk):    print bkif __name__ == '__main__':    THREAD_NUM = 3    bk_list = ['aaa', 'bbb', 'ccc', 'ddd', 'eee', 'fff', 'ggg', 'hhh', 'iii', 'jjj', 'kkk']    start_book_threads(bk_list, deal_book)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.