import time import random from multiprocessing import Process,Queue def producer(q,name,food): for i in range(4): time.sleep(random.random()) f = "{}生产出一个{}".format(name,food) print(f) q.put(f) def consumer(q,name): while True: food = q.get() if food is None: print("{}获取空,退出".format(name)) break time.sleep(random.random()) print("{}消费了一个{}".format(name,food)) if __name__ == '__main__': q = Queue(10) p1 = Process(target=producer,args=(q,"生产者1号","包子")) p2 = Process(target=producer,args=(q,"生产者2号","馒头")) c1 = Process(target=consumer,args=(q,"消费者1号")) c2 = Process(target=consumer,args=(q,"消费者2号")) c3 = Process(target=consumer,args=(q,"消费者3号")) p1.start() p2.start() c1.start() c2.start() c3.start() p1.join() p2.join() q.put(None) q.put(None) q.put(None)
import time import random from multiprocessing import Process,JoinableQueue def producer(q,name,food): for i in range(4): time.sleep(random.random()) f = "{}生产出一个{}".format(name,food) print(f) q.put(f) q.join() #生产周期变长,要等到所生产的数据被处理完,这个子进程才结束 def consumer(q,name): while True: food = q.get() time.sleep(random.random()) print("{}消费了一个{}".format(name,food)) q.task_done() if __name__ == '__main__': q = JoinableQueue(10) p1 = Process(target=producer,args=(q,"生产者1号","包子")) p2 = Process(target=producer,args=(q,"生产者2号","馒头")) c1 = Process(target=consumer,args=(q,"消费者1号")) c2 = Process(target=consumer,args=(q,"消费者2号")) c3 = Process(target=consumer,args=(q,"消费者3号")) p1.start() p2.start() c1.daemon = True #设置为守护进程,主进程中的代码执行完毕之后,该守护进程自动结束 c2.daemon = True c3.daemon = True c1.start() c2.start() c3.start() p1.join() #感知一个进程的结束 p2.join()