Python之生产者&、消费者模型

多线程中的生产者和消费者模型:

生产者和消费者可以用多线程实现,它们通过Queue队列进行通信。

import time,random
import Queue,threading

q = Queue.Queue()
def Producer(name):
  count = 0
  while count <20:
    time.sleep(random.randrange(3))#随机时间间隔
    q.put(count)
    print('Producer %s has produced %s baozi..' %(name, count))
    count +=1
def Consumer(name):
  count = 0
  while count <20:
    time.sleep(random.randrange(4))
    if not q.empty():
        data = q.get()
        print(data)
        print('33[32;1mConsumer %s has eat %s baozi...33[0m' %(name, data))
    else:
        print("-----no baozi anymore----")
    count +=1
p1 = threading.Thread(target=Producer, args=('A',))
c1 = threading.Thread(target=Consumer, args=('B',))
p1.start()
c1.start()
原文地址:https://www.cnblogs.com/ahaii/p/5340513.html