用 threading.Event() 也可以实现生产者/消费者模式
(自己拍脑袋想出来的,无法知道其正确性,请大神告知为谢!)
import threading
import time
import random products = 20 class Producer(threading.Thread):
'''生产者'''
ix = [0] # 生产者实例个数
# 闭包,必须是数组,不能直接 ix = 0 def __init__(self):
super().__init__()
self.ix[0] += 1
self.setName('生产者' + str(self.ix[0])) def run(self):
global producer_signal, products while True:
if products < 10:
if not producer_signal.is_set(): producer_signal.set()
products += 1;
print("{}:库存告急。我努力生产了1件产品,现在产品总数量 {}".format(self.getName(), products))
else:
print("{}:库存充足。我努力生产了0件产品,现在产品总数量 {}".format(self.getName(), products))
if producer_signal.is_set(): producer_signal.wait()
time.sleep(random.randrange(1,4)) class Consumer(threading.Thread):
'''消费者'''
ix = [0] # 消费者实例个数
# 闭包,必须是数组,不能直接 ix = 0 def __init__(self):
super().__init__()
self.ix[0] += 1
self.setName('消费者' + str(self.ix[0])) def run(self):
global consumer_signal, products while True:
if products > 1:
if not consumer_signal.is_set(): consumer_signal.set()
products -= 1;
print("{}:我消费了1件产品,现在产品数量 {}".format(self.getName(), products))
else:
print("{}:我消费了0件产品。现在产品数量 {}".format(self.getName(), products))
if consumer_signal.is_set(): consumer_signal.wait()
time.sleep(random.randrange(2,6)) if __name__ == "__main__": producer_signal = threading.Event()
consumer_signal = threading.Event() for i in range(2):
p = Producer()
p.start() for i in range(10):
c = Consumer()
c.start()