生产与消费者模式

目的:提高效率

定义:在并发编程中使用生产者与消费者模式能够解决大部分并发问题。该模式通过平衡生产线与消费线的工作能了来提高程序的整体处理数据的速度。

案例:
在这里插入图片描述
代码:

import time
from queue import Queue
from threading import Thread
q=Queue()
#消费者方法
def consumer(name):
    while True:
        print(name,'吃了',q.get())
        time.sleep(1.5)
  #生产者方法
def cooker(name):
    count=1
    while True:
        q.put("包子%d"%count)
        print(name,'------做了包子------',count)
        count+=1
        time.sleep(1)
      #主进程
if __name__ == '__main__':
    c=Thread(target=cooker,args=('john',))
    consum1=Thread(target=consumer,args=('小花',))
    consum2=Thread(target=consumer,args=('小红',))
    c.start()
    consum1.start()
    consum2.start()

猜你喜欢

转载自blog.csdn.net/qq_39062888/article/details/88562100