python 多線程 實現 生產者-消費者(四)

from time import ctime
from time import sleep
import Queue
import random

import my_thread


def writeQ(queue):
    print 'producing object for Q...'
    queue.put('xxx')
    print 'Queue size:', queue.qsize()


def readQ(queue):
    val = queue.get()
    print 'consume object for Q...Queue size:', queue.qsize()


def writer(queue, loops):
    for i in range(loops):
        writeQ(queue)
        sleep(random.randint(1, 3))


def reader(queue, loops):
    for i in range(loops):
        readQ(queue)
        sleep(random.randint(2, 5))

funcs = [reader, writer]
nfuncs = range(len(funcs))

def main():
    nloops = random.randint(2, 5)
    threads = []
    print 'nloops:', nloops

    q = Queue.Queue(32)

    for i in nfuncs:
        t = my_thread.MyThread(func=funcs[i], args=(q, nloops), name=funcs[i].__name__)
        threads.append(t)

    for i in nfuncs:
        threads[i].start()

    for i in nfuncs:
        threads[i].join()

    print 'main end =========================='

if __name__ == '__main__':
    main()


結果:
nloops: 2
start=== reader at Sat May 07 14:01:44 2016
start=== writer at Sat May 07 14:01:44 2016
producing object for Q…
Queue size: 0consume object for Q…Queue size:
0
producing object for Q…
Queue size: 1
consume object for Q…Queue size: 0
end===== writer at Sat May 07 14:01:49 2016
end===== reader at Sat May 07 14:01:53 2016
main end ==========================

Queue中的put 和get都有一個block參數,默認是True,如果設置爲False,則會在empty和full時拋出異常

Exception in thread reader:
Traceback (most recent call last):
File “C:\Python27\lib\threading.py”, line 801, in __bootstrap_inner
self.run()
File “D:\Users\zhangruixia\PycharmProjects\min_spider\my_thread.py”, line 17, in run
self.res = apply(self.func, self.args)
File “D:/Users/zhangruixia/PycharmProjects/min_spider/test8_reader_writer.py”, line 28, in reader
readQ(queue)
File “D:/Users/zhangruixia/PycharmProjects/min_spider/test8_reader_writer.py”, line 16, in readQ
val = queue.get(False)
File “C:\Python27\lib\Queue.py”, line 165, in get
raise Empty
Empty

發佈了88 篇原創文章 · 獲贊 6 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章