生产消费者模型(进程通信,队列)

# Author:Winter Liu is coming!
# 队列自动加锁
import time import random from multiprocessing import Process, Queue def customer(q, name): while True: food = q.get() if food: print("{}吃了{}".format(name, food)) else: break def producer(q, name, food): for i in range(6): time.sleep(random.random()) print("{}:{}做了{}".format(i+1, name, food)) q.put("{}的{}".format(name, food)) if __name__ == __main__: q = Queue() # 创建队列,并将队列传给子进程 p1 = Process(target=producer, args=(q, "大嘴", "馒头")) p2 = Process(target=producer, args=(q, "小郭", "炊饼")) c = Process(target=customer, args=(q, "小六")) p1.start() p2.start() c.start() p1.join() # 主进程等待生产子进程结束 p2.join() q.put(None) # 生产子进程结束后在队列中放入标志,告诉消费子进程生产结束

 

生产消费者模型(进程通信,队列)

上一篇:Linux磁盘分区(三)之查看磁盘分区常用命令


下一篇:Shell