python之生产者消费者模型实现详解
Python  /  管理员 发布于 8年前   207
代码及注释如下
#Auther Bob#--*--conding:utf-8 --*--#生产者消费者模型,这里的例子是这样的,有一个厨师在做包子,有一个顾客在吃包子,有一个服务员在储存包子,这个服务员我们就可以用queue来实现import threadingimport queueimport time '''def consumer(p,que): id = que.get() print("[%s]来吃包子了,我吃到的包子的名字是[%s]" %(p,id)) def prodcer(p,que): print("[%s]做了2个包子" %(p)) que.put("baozi[1]") print("baozi[1]做好了") que.put("baozi[2]") print("baozi[2]做好了") if __name__ == '__main__': que = queue.Queue() p = threading.Thread(target=prodcer,args=("Bob",que)) c1 = threading.Thread(target=consumer,args=("c1",que)) c2 = threading.Thread(target=consumer, args=("c2", que)) c3 = threading.Thread(target=consumer, args=("c3", que)) p.start() c1.start() c2.start() c3.start() # p.join() ''' #上面这个例子,如果没有包子了,但是厨师会不知道,厨师也不会继续做包子,而没有吃到包子的人会一直等待,程序会一直不结束 #我们可以这样做,消费者发现没有包子了,告诉服务员,服务员在告诉厨师,这里我们就会遇到task.down def consumer(p): id = que.get() print("[%s]来吃包子了,我吃到的包子的名字是[%s]" %(p,id)) que.task_done() #如归队列为空了,则会通知que.join,que.join就不会阻塞了 """ def prodcer(p): while True: if que.qsize() < 3: # time.sleep(1) for i in range(2): print("[%s]做了包子[%d]" %(p,i)) que.put(i) que.join() #如果队列一直不为空,则que.join会一直阻塞,如果队列为空,则que.join就不阻塞了"""def prodcer(p): while True: # time.sleep(1) for i in range(2): print("[%s]做了包子[%d]" %(p,i)) que.put(i) que.join() #如果队列一直不为空,则que.join会一直阻塞,如果队列为空,则que.join就不阻塞了if __name__ == '__main__': que = queue.Queue() p = threading.Thread(target=prodcer,args=("Bob1",)) p2 = threading.Thread(target=prodcer, args=("Bob2",)) c1 = threading.Thread(target=consumer,args=("c1",)) c2 = threading.Thread(target=consumer, args=("c2",)) c3 = threading.Thread(target=consumer, args=("c3",)) c4 = threading.Thread(target=consumer, args=("c4",)) c5 = threading.Thread(target=consumer, args=("c5",)) c6 = threading.Thread(target=consumer, args=("c6",)) p.start() p2.start() c1.start() c2.start() c3.start() c4.start() c5.start() c6.start() # p.join() # que.task_done()以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
test1 在
opencode + Oh-my-openagent,我的第一个免费的ai编程智能体管家:Sisyphus中评论 test..122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..Zita 在
Google AI Studio升级全栈 vibe coding体验,可直接构建带登录和数据库的应用中评论 111222..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号
