# coding:utf-8
import os
import time
import random
from multiprocessing import Process, JoinableQueue
def producer(food, queue):
for i in range(2):
time.sleep(random.randint(1, 3))
info = "%s%s" % (food, i)
queue.put(info)
print("%s生成了%s" % (os.getpid(), info))
queue.join()
print("%s生产结束." % os.getpid())
def consumer(queue):
while 1:
info = queue.get()
print("%s吃了%s" % (os.getpid(), info))
time.sleep(random.randint(1, 3))
queue.task_done()
if __name__ == '__main__':
queue = JoinableQueue()
p1 = Process(target=producer, args=("包子", queue,))
p2 = Process(target=producer, args=("馅饼", queue,))
c1 = Process(target=consumer, args=(queue,))
c2 = Process(target=consumer, args=(queue,))
c1.daemon = True
c2.daemon = True
p_lst = [p1, p2, c1, c2]
for p in p_lst:
p.start()
p1.join()
p2.join()
print("主程序结束.")
# 5752生成了馅饼0
# 3200吃了馅饼0
# 6852生成了包子0
# 10044吃了包子0
# 5752生成了馅饼1
# 6852生成了包子1
# 3200吃了馅饼1
# 10044吃了包子1
# 5752生产结束.
# 6852生产结束.
# 主程序结束.