code
import threadingfrom
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_')
t2 = thread(target=consumer, name=f"
cos_")
t1.start()
t2.start()
for t in
threads: # 等待所有執行緒完成
t.join()
NSCondition 多執行緒解決生產者消費者問題
import viewcontroller.h inte ce viewcontroller 資料緩衝區 property strong,nonatomic nsmutablearray products 執行緒鎖 property strong,nonatomic nscondition cond...
條件變數 互斥鎖解決生產者消費者模型
實現 int num 0 pthread mutex t mutex pthread cond t condition void producer void arg void cusumer void arg num pthread mutex unlock mutex 首先,條件變數一定要和互斥鎖...
生產者消費者執行緒
include include include includeusing namespace std typedef int semaphore 訊號量是一種特殊的整型變數 const int size of buffer 5 緩衝區長度 const unsigned short producers...