原文链接: Python 线程 条件锁 生产者消费者模型
创建多个生产者和消费者,并且加上条件锁,避免线程冲突
import threading
from threading import Thread
from threading import Condition
import time
import random
c = Condition() # 条件锁
itemNum = 0
item = 0
def consumer(): # 消费者
global item # 商品编号
global itemNum
c.acquire() # 锁住资源
while 0 == itemNum: # 如无产品则让线程等待
print("consumer :挂起.", threading.current_thread().name, threading.current_thread())
c.wait()
itemNum -= 1
print("consumer : 消费 %s." % item, itemNum, threading.current_thread().name, threading.current_thread())
c.release() # 解锁资源
def producer(): # 生产者
global item # 商品编号
global itemNum
time.sleep(3)
c.acquire() # 锁住资源
item = random.randint(1, 1000)
itemNum += 1
print("producer : 生产 %s." % item, threading.current_thread().name, threading.current_thread())
c.notifyAll() # 唤醒所有等待的线程--》其实就是唤醒消费者进程
c.release() # 解锁资源
threads = [] # 线程收集列表
for i in range(0, 4): # 使用循环完成生产者与消费者线程的建立
t1 = Thread(target=producer, name=f'pro_{i}')
t2 = Thread(target=consumer, name=f"cos_{i}")
t1.start()
t2.start()
threads.append(t1)
threads.append(t2)
for t in threads: # 等待所有线程完成
t.join()
生产和 消费的线程不一定是创建时对应的
consumer :挂起. cos_0 <Thread(cos_0, started 4612)>
consumer :挂起. cos_1 <Thread(cos_1, started 12068)>
consumer :挂起. cos_2 <Thread(cos_2, started 6504)>
consumer :挂起. cos_3 <Thread(cos_3, started 9400)>
producer : 生产 543. pro_0 <Thread(pro_0, started 6900)>
producer : 生产 590. pro_1 <Thread(pro_1, started 7084)>
consumer : 消费 590. 1 cos_3 <Thread(cos_3, started 9400)>
consumer : 消费 590. 0 cos_1 <Thread(cos_1, started 12068)>
consumer :挂起. cos_2 <Thread(cos_2, started 6504)>
consumer :挂起. cos_0 <Thread(cos_0, started 4612)>
producer : 生产 121. pro_2 <Thread(pro_2, started 4036)>
consumer : 消费 121. 0 cos_2 <Thread(cos_2, started 6504)>
consumer :挂起. cos_0 <Thread(cos_0, started 4612)>
producer : 生产 799. pro_3 <Thread(pro_3, started 5892)>
consumer : 消费 799. 0 cos_0 <Thread(cos_0, started 4612)>