生产者消费者模型
第一种实现方案
生产者生产完,让生生产告诉主进程他们已经结束,让后主进程给消费者发一个结束指令,消费者拿出所有产品,等拿到结束指令结束
from multiprocessing import Queue,Process,JoinableQueue def producer(name,food,q): for i in range(10): res = "%s%s"%(food,i) time.sleep(random.randint(1,2)) q.put(res) print('厨师[%s]做了[%s]%s'%(name,food,i)) def consumer(name,q): while True: res = q.get() if res is None:break time.sleep(random.randint(1,3)) print('吃货[%s]吃了[%s]'%(name,res)) if __name__ == '__main__': q = Queue() p1 = Process(target=producer,args=('刘大厨','包子',q)) p2 = Process(target=producer,args=('李大厨','馒头',q)) p3 = Process(target=producer,args=('林大厨','辣条',q)) c1 = Process(target=consumer,args=('张三',q)).start() c2 = Process(target=consumer,args=('李四',q)).start() p1.start() p2.start() p3.start() p1.join() p2.join() p3.join() q.put(None) q.put(None) print('主进程的活干完了waiting...............')
第二种实现方案
第二种实现方案,就是在用JoinableQueue,等消费者拿完所有的产品结束,q.task_done()告诉队列结束,q.join()结束意味着所有都拿完,让消费者作为主进程的守护进程,
与主进程一同结束
from multiprocessing import Queue,Process,JoinableQueue def producer(name,food,q): for i in range(10): res = "%s%s"%(food,i) time.sleep(random.randint(1,2)) q.put(res) print('厨师[%s]做了[%s]%s'%(name,food,i)) def consumer(name,q): while True: res = q.get() # if res is None:break time.sleep(random.randint(1,3)) print('吃货[%s]吃了[%s]'%(name,res)) q.task_done() if __name__ == '__main__': q = JoinableQueue() p1 = Process(target=producer,args=('刘大厨','包子',q)) p2 = Process(target=producer,args=('李大厨','馒头',q)) p3 = Process(target=producer,args=('林大厨','辣条',q)) c1 = Process(target=consumer,args=('张三',q)) c2 = Process(target=consumer,args=('李四',q)) c1.daemon = True c2.daemon = True p1.start() p2.start() p3.start() c1.start() c2.start() p1.join() p2.join() p3.join() q.join() print('主进程的活干完了waiting...............')