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

案例:厨师做包子和顾客吃包子的问题。
'''
import threading
import queue,time

q = queue.Queue(maxsize=10)

#生产者
def producer(name):
    count = 1
    while True:
        q.put('包子%d'%count)
        print('生产了包子:%d'%count)
        count += 1
        time.sleep(1)

def consumer(name):
    count = 1
    while True:
        print('[%s]取到了[%s],并且吃了它'%(name,q.get()))
        time.sleep(1)

if __name__ == "__main__":
    p = threading.Thread(target=producer,args=('张大厨',))
    a = threading.Thread(target=consumer,args=('A',))
    b = threading.Thread(target=consumer,args=('B',))
    p.start()
    a.start()
    b.start()

 

相关文章:

  • 2021-12-05
  • 2021-09-20
  • 2021-12-16
  • 2021-12-15
  • 2021-04-15
  • 2021-04-15
  • 2021-12-05
  • 2021-05-17
猜你喜欢
  • 2022-02-11
  • 2022-12-23
  • 2022-12-23
  • 2021-11-24
  • 2022-01-12
相关资源
相似解决方案