生产者消费者模型
1、程序中有两类角色,产生数据,消费数据
2、解决问题是解决程序解偶合,平衡生产者和消费者之间的速度差
from multiprocessing import Process,Queue import time def producer(q): for i in range(3): res="包子%s" % i time.sleep(1) q.put(res) print("生产者生产了%s" % res) def consumer(q): while True: time.sleep(1) res=q.get() if res==None: break print("消费者吃了%s" % res) if __name__ == "__main__": q=Queue() p=Process(target=producer,args=(q,)) c = Process(target=consumer, args=(q,)) p.start() c.start() p.join() q.put(None) print("主线程")
JoinableQueue
from multiprocessing import Process,Queue,JoinableQueue import time def producer(q): for i in range(3): res="包子%s" % i time.sleep(1) q.put(res) print("生产者生产了%s" % res) q.join() def consumer(q): while True: time.sleep(1) res=q.get() if res==None: break print("消费者吃了%s" % res) q.task_done() if __name__ == "__main__": q=JoinableQueue() p=Process(target=producer,args=(q,)) c = Process(target=consumer, args=(q,)) p.start() c.start() print("主线程")