首页 > 代码库 > 【Python@Thread】queue模块-生产者消费者问题

【Python@Thread】queue模块-生产者消费者问题

python通过queue模块来提供线程间的通信机制,从而可以让线程分项数据。

个人感觉queue就是管程的概念

一个生产者消费者问题

 1 from random import randint
 2 from threading import Thread
 3 from queue import Queue
 4 from time import sleep
 5 
 6 
 7 def writeq(queue):
 8     print(starting put queue...)
 9     queue.put(hahaha, 1)          #1表示在有可用空间前,阻塞
10     print(size now, queue.qsize())
11 
12 
13 def readq(queue):
14     print(starting get queue...)
15     val = queue.get(1)              #1表示在有可用元素前阻塞
16     print(consume from queu...size now, queue.qsize())
17 
18 
19 def writer(queue, loops):
20     for i in range(loops):
21         writeq(queue)
22         sleep(randint(1, 3))
23 
24 
25 def reader(queue, loops):
26     for i in range(loops):
27         readq(queue)
28         sleep(randint(2, 5))
29 
30 
31 funcs = [writer, reader]
32 
33 
34 def main():
35     nloops = randint(2, 5)
36     q = Queue(32)
37 
38     threads = []
39     for i in range(len(funcs)):
40         t = Thread(target=funcs[i], args=(q, nloops))
41         threads.append(t)
42 
43     for i in range(len(funcs)):
44         threads[i].start()
45 
46     for i in range(len(funcs)):
47         threads[i].join()
48 
49     print(all done)
50 
51 if __name__ == __main__:
52     main()

输出结果:

技术分享

 

【Python@Thread】queue模块-生产者消费者问题