python-生产者消费者模型
Posted benchdog
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python-生产者消费者模型相关的知识,希望对你有一定的参考价值。
生产者消费者是通过一个容器来解决生产者和消费者的强耦合问题。生产者和消费者不直接通讯,而通过阻塞队列进行通信。阻塞队列就相当一个缓冲区,平衡了生产者和消费者的处理能力。
import time,random import queue,threading q = queue.Queue() def Producer(name): count = 0 while count <10: print("making........") time.sleep(5) q.put(count) print(‘Producer %s has produced %s baozi..‘ %(name, count)) count +=1 #q.task_done() q.join() print("ok......") def Consumer(name): count = 0 while count <10: time.sleep(random.randrange(4)) # if not q.empty(): # print("waiting.....") #q.join() data = q.get() print("eating....") time.sleep(4) q.task_done() #print(data) print(‘