執行結果:#include #include #include #include /* 靜態方式初始化乙個互斥鎖和乙個條件變數 */
static pthread_mutex_t mutex = pthread_mutex_initializer;
static pthread_cond_t cond = pthread_cond_initializer;
/* 指向執行緒控制塊的指標 */
static pthread_t tid1;
static pthread_t tid2;
/* 函式返回值檢查 */
static void check_result(char* str,int result)
else }
/* 生產者生產的結構體資料,存放在煉表裡 */
struct node
;struct node* head = null; /* 煉表頭,是共享資源 */
/* 消費者執行緒入口函式 */
static void* consumer(void* parameter)
/*pthread_cond_wait()會先對mutex解鎖,
然後阻塞在等待佇列,直到獲取條件變數被喚醒,
被喚醒後,該執行緒會再次對mutex上鎖,成功進入臨界區。
*/p_node = head; /* 拿到資源 */
head = head->n_next; /* 頭指標指向下乙個資源 */
/* 列印輸出 */
printf("consume %d\n",p_node->n_number);
free(p_node); /* 拿到資源後釋放節點占用的記憶體 */
} pthread_mutex_unlock(&mutex); /* 釋放互斥鎖 */
return 0;
}/* 生產者執行緒入口函式 */
static void* product(void* patameter)
else
}}/* 使用者應用入口 */
int main()
while(i--);
}
多執行緒程式設計 條件變數
條件變數 條件變數是利用執行緒間共享的全域性變數進行同步的一種機制,主要包括兩個動作 乙個執行緒等待 條件變數的條件成立 而掛起 另乙個執行緒使 條件成立 給出條件成立訊號 為了防止競爭,條件變數的使用總是和乙個互斥鎖結合在一起。1.建立和登出 條件變數和互斥鎖一樣,都有靜態和動態兩種建立方式,靜態...
多執行緒程式設計 條件變數
自 1 引言 條件變數是一種同步機制,允許執行緒掛起,直到共享資料上的某些條件得到滿足。條件變數上的基本操作有 觸發條件 當條件變為true 時 等待條件,掛起執行緒直到其他執行緒觸發條件。條件變數要和互斥量相聯結,以避免出現條件競爭 乙個執行緒預備等待乙個條件變數,當它在真正進入等待之前,另乙個執...
Linux多執行緒程式設計 條件變數
include int pthread cond init pthread cond t cv,const pthread condattr t cattr 返回值 函式成功返回0 任何其他返回值都表示錯誤初始化乙個條件變數。當引數cattr為空指標時,函式建立的是乙個預設的條件變數。否則條件變數的...