首页 > 代码库 > 【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模块-生产者消费者问题
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。