"""
某市有5工厂,因原材料有限,所以每个厂家一天只能生产100万个口罩。每个订单10万个,工时10秒钟。
避免产出过剩,只有接收到需求订单后再开始生产。
这5个工厂生产出来的口罩,统一供给同一个药店。
"""
import threading,time
from random import randint
class Producer(threading.Thread):
def run(self):
global L
n = 20
with lock_con:
print(f'{self.name}producer acquire lock')
while True:
print(f'{self.name}厂家准备就绪,等待通知')
print(f'{self.name}producer release lock before wait')
lock_con.wait()
print(f'{self.name}producer acquire lock after wait')
time.sleep(1)
val = randint(1, 100)
L.append(val)
n -= 10
print(f'{self.name}厂家耗时2秒生产出一批商品: {val},并放到药店。现在药店上是口罩有: {L}')
if n <= 0:
print(f'{self.name}厂家没有原料了,停止生产')
break
print(f'{self.name}producer release lock')
class Consumer(threading.Thread):
def run(self):
global L
while True:
if not lock_con.acquire(timeout=3):
print('在药店门口等了3秒钟,药店没有开门')
continue
print(f'consumer {self.name} acquire lock')
print('药店开门了')
if len(L) == 0:
flg = 0
for t_tmp in threads:
if t_tmp.is_alive():
flg = 1
break
if not flg:
print('没有正在营业的生产商')
lock_con.release()
break
print('药店里没有口罩,随机给其中一个厂家下单')
lock_con.notify()
print(f'consumer {self.name} notify')
else:
print('消费一个批次的口罩,耗时2秒')
del_data = L[0]
time.sleep(1)
del L[0]
lock_con.release()
print(f'consumer {self.name} release lock')
time.sleep(1) # 等一会,让厂家获取到lock
if __name__ == '__main__':
L=[]
lock_con=threading.Condition()
threads=[]
for i in range(5):
threads.append(Producer())
for t in threads:
t.start()
ct = Consumer(name='consumer')
ct.start()
for t in threads:
t.join()
ct.join()
可以手动修改notify为notify_all,看一下这两个的区别。
相关链接
https://stackoverflow.com/questions/11195140/break-or-exit-out-of-with-statement
https://blog.csdn.net/brucewong0516/article/details/84587522
https://www.jianshu.com/p/b6aba528e4e7