Python多线程-生产者消费者模型
用多线程和队列来实现生产者消费者模型
# -*- coding:utf-8 -*- __author__ = "MuT6 Sch01aR" import threading import queue import time q = queue.Queue() def Producer(name): count = 1 while True: q.put("面包%s" %count) print("[%s]做了[%s]个面包" %(name,count)) count +=1 time.sleep(1) def Consumer(name): while True: print("[%s]取得[%s]并吃了它" %(name,q.get())) time.sleep(1) t1 = threading.Thread(target=Producer,args=("掌柜",)) t2 = threading.Thread(target=Consumer,args=("张三",)) t3 = threading.Thread(target=Consumer,args=("李四",)) t1.start() t2.start() t3.start()
运行结果
生产一个消费一个,两个消费者是按照顺序一个一个地消费