from multiprocessing import Process, JoinableQueue
import time
import random
def producer(name, food, q):
for i in range(5):
data = '%s生产了%s%s' % (name, food, i)
time.sleep(random.randint(1, 3))
print(data)
q.put('%s生产的%s%s' % (name, food, i))
def consumer(name, q):
while True:
food = q.get()
time.sleep(random.randint(1, 3))
print('%s吃了%s' % (name, food))
q.task_done() # 告诉队列已经从里面取出一个数据并处理完毕
if __name__ == '__main__':
q = JoinableQueue() # 存一个数据,内部计数+1,取一个,计数器—1
p1 = Process(target=producer, args=('egon', '包子', q))
p2 = Process(target=producer, args=('tank', '火锅', q))
c1 = Process(target=consumer, args=('小明', q))
c2 = Process(target=consumer, args=('天王盖地虎', q))
p1.start()
p2.start()
c1.daemon = True
c2.daemon = True
p1.join() # 让主进程等待子进程运行结束之后再运行
p2.join()
c1.start()
c2.start()
# p1.join() # 让主进程等待子进程运行结束之后再运行
# p2.join()
q.join() # 基于JoinableQueue,q.join() 当计数器为0的时候 才往后运行