11 改进版通过队列实现一个生产者消费者模型
import time from multiprocessing import Process,Queue #生产者 def producer(q): for i in range(10): time.sleep(0.7) s = '大包子%s号'%i print(s+'新鲜出炉,拿去用') q.put(s) def consumer(q): while 1: time.sleep(0.2) try: baozi = q.get_nowait() #不合适,因为无法确定做的块,还是吃的块,如果按照这样的写法,你吃的快的话,那么这个消费者的程序就直接结束了,不能满足需求 except Exception: break print(baozi+'被吃了') if __name__ == '__main__': q = Queue(10) pro_p = Process(target=producer,args=(q,)) con_p = Process(target=consumer,args=(q,)) pro_p.start() con_p.start()