首页 > 编程语言 > 详细

python-生产者消费者模型

时间:2018-06-14 10:02:59      阅读:156      评论:0      收藏:0      [点我收藏+]

生产者消费者是通过一个容器来解决生产者和消费者的强耦合问题。生产者和消费者不直接通讯,而通过阻塞队列进行通信。阻塞队列就相当一个缓冲区,平衡了生产者和消费者的处理能力。

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(\033[32;1mConsumer %s has eat %s baozi...\033[0m %(name, data))
    # else:
    #     print("-----no baozi anymore----")
        count +=1

p1 = threading.Thread(target=Producer, args=(A君,))
c1 = threading.Thread(target=Consumer, args=(B君,))
c2 = threading.Thread(target=Consumer, args=(C君,))
c3 = threading.Thread(target=Consumer, args=(D君,))

p1.start()
c1.start()
c2.start()
c3.start()

 

python-生产者消费者模型

原文:https://www.cnblogs.com/benchdog/p/9181109.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!