Python 執行緒 條件鎖 生產者消費者模型
阿新 • • 發佈:2020-12-26
code
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 # 商品編號 globalitemNum 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 = [] # 執行緒收集列表 fori 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()