生产者消费者模型
from multiprocessing import Process,Queue,JoinableQueue
import time
import random
# def producer(name,product):
# 上述写法错误,在开子进程时,不传入q,
# 则子进程的名称空间中就没有队列对象q,无法对队列进行操作
def producer(name,product,q):
for i in range(1,6):
data = "%-10s正在生产【%s%s】" % (name,product,i)
print(data)
# 模拟生产延迟
time.sleep(random.randint(1,3))
# 放入队列
food = "%s%s"%(product,i)
q.put(food)
def consumer(name,q):
while True:
# 从队列中取出food,若无则等待 q.get_nowait()不等待,直接报错
food = q.get()
time.sleep(random.randint(1,3))
print("%-15s吃了【%s】" %(name,food))
# 在完成一项工作之后,q.task_done()函数向任务已经完成的队列发送一个信号
# 队列计数减一,当计数为零时,执行q.join()。q.join() 实际上意味着等到队列为空,再执行别的操作
q.task_done()
if __name__ == '__main__':
q = JoinableQueue()
# q = Queue()
p1 = Process(target = producer,args=("Jil","手打鱼丸",q))
p2 = Process(target = producer,args=("Fishball","姜糖鱼丸",q))
c1 = Process(target = consumer,args=("small piggy1",q))
c2 = Process(target = consumer,args=("small piggy2",q))
# 必须start开始进程
p1.start()
p2.start()
# 在消费者进行开始前,将其设置成守护进程,与主程序共存亡
c1.daemon = True
c2.daemon = True
c1.start()
c2.start()
# 当p1 p2子进程运行完成时,主程序继续运行
p1.join()
p2.join()
# 当队列计数为零时,即队列为空时,主程序继续运行
q.join()
print("【猪猪】把【鱼丸】吃完啦!")