生产者生产的东西放到队列里,消费者消费掉东西。

import time
import random
from multiprocessing import Process,Queue
def consumer(q,name): # 消费者
while True:
food = q.get()
if food is None: # 如果消费完了,就会得到一个None,然后结束
print('%s获取到了一个空'%name)
break
print('%s消费了%s' % (name,food))
time.sleep(random.randint(1,3))

def producer(name,food,q): # 生产者
for i in range(4):
time.sleep(random.randint(1,3))
f = '%s生产了%s%s'%(name,food,i)
print(f)
q.put(f)

if __name__ == '__main__':
q = Queue(20)
p1 = Process(target=producer,args=('小明','包子',q))
p2 = Process(target=producer, args=('小红','大饼', q))
c1 = Process(target=consumer, args=(q,'小狗'))
c2 = Process(target=consumer, args=(q,'小猪'))
p1.start()
p2.start()
c1.start()
c2.start()
p1.join() # 感知子进程生产完了
p2.join() # 感知子进程生产完了
q.put(None) # 就放入一个None
q.put(None) # 就放入一个None