python之生产者消费者模型

#Auther Bob
#--*--conding:utf-8 --*--
#生产者消费者模型,这里的例子是这样的,有一个厨师在做包子,有一个顾客在吃包子,有一个服务员在储存包子,这个服务员我们就可以用queue来实现
import threading
import queue
import time

'''
def consumer(p,que):
    id = que.get()
    print("[%s]来吃包子了,我吃到的包子的名字是[%s]" %(p,id))

def prodcer(p,que):
    print("[%s]做了2个包子" %(p))
    que.put("baozi[1]")
    print("baozi[1]做好了")
    que.put("baozi[2]")
    print("baozi[2]做好了")

if __name__ == '__main__':
    que = queue.Queue()
    p = threading.Thread(target=prodcer,args=("Bob",que))
    c1 = threading.Thread(target=consumer,args=("c1",que))
    c2 = threading.Thread(target=consumer, args=("c2", que))
    c3 = threading.Thread(target=consumer, args=("c3", que))
    p.start()
    c1.start()
    c2.start()
    c3.start()
    # p.join()


'''


#上面这个例子,如果没有包子了,但是厨师会不知道,厨师也不会继续做包子,而没有吃到包子的人会一直等待,程序会一直不结束



#我们可以这样做,消费者发现没有包子了,告诉服务员,服务员在告诉厨师,这里我们就会遇到task.down

def consumer(p):
    id = que.get()
    print("[%s]来吃包子了,我吃到的包子的名字是[%s]" %(p,id))
    que.task_done()   #如归队列为空了,则会通知que.join,que.join就不会阻塞了

"""

def prodcer(p):
    while True:
        if que.qsize() < 3:
            # time.sleep(1)
            for i in range(2):
                print("[%s]做了包子[%d]" %(p,i))
                que.put(i)
            que.join()  #如果队列一直不为空,则que.join会一直阻塞,如果队列为空,则que.join就不阻塞了
"""
def prodcer(p):
    while True:
        # time.sleep(1)
        for i in range(2):
            print("[%s]做了包子[%d]" %(p,i))
            que.put(i)
        que.join()  #如果队列一直不为空,则que.join会一直阻塞,如果队列为空,则que.join就不阻塞了
if __name__ == '__main__':
    que = queue.Queue()
    p = threading.Thread(target=prodcer,args=("Bob1",))
    p2 = threading.Thread(target=prodcer, args=("Bob2",))
    c1 = threading.Thread(target=consumer,args=("c1",))
    c2 = threading.Thread(target=consumer, args=("c2",))
    c3 = threading.Thread(target=consumer, args=("c3",))
    c4 = threading.Thread(target=consumer, args=("c4",))
    c5 = threading.Thread(target=consumer, args=("c5",))
    c6 = threading.Thread(target=consumer, args=("c6",))
    p.start()
    p2.start()
    c1.start()
    c2.start()
    c3.start()
    c4.start()
    c5.start()
    c6.start()
    # p.join()
    # que.task_done()

  

原文地址:https://www.cnblogs.com/bainianminguo/p/7426273.html