Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 關於Linux

POSIX 多執行緒:條件變數 pthread_cond_t 詳解

互斥鎖只解決了「誰能進臨界區」,卻沒辦法表達「要等到某個條件成立才能繼續」。條件變數正是為填補這個缺口而生:它讓執行緒阻塞等待,並由其他執行緒在條件改變時發出通知。實務上它幾乎總是與互斥鎖搭在一起使用。

基本操作

條件變數的型別是 pthread_cond_t(作用近似 Windows 的事件物件)。

初始化:int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *cond_attr); cond 指向條件變數,cond_attr 是它的屬性結構,用來指定「行程內可用」或「行程間可用」,預設是 PTHREAD_PROCESS_PRIVATE。注意只有未被使用時才能重新初始化或釋放。

釋放:pthread_cond_destroy(pthread_cond_t cond)

等待

extern int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);

它會解開 mutex 指向的鎖,然後把執行緒阻塞在 cond 上。執行緒可以被 pthread_cond_signal 或 pthread_cond_broadcast 喚醒。要緊的是:條件變數只負責阻塞與喚醒,「條件是否成立」的判斷必須由你自己寫(例如某變數是否為 0)。被喚醒後要重新檢查條件,若仍不滿足就繼續等待——這個迴圈通常用 while 而非 if 撰寫。

另一個變體是 pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime);,多一個絕對時間參數,逾時即使條件未成立也會解除阻塞。

通知

extern int pthread_cond_signal(pthread_cond_t *cond); 釋放一個阻塞在該條件變數上的執行緒;若有多個在等,究竟哪一個被喚醒由排程策略決定。關鍵提醒:呼叫這個函式時必須由保護條件變數的同一把互斥鎖保護,否則「條件已滿足」的訊號可能在「檢查條件」與「呼叫 pthread_cond_wait」之間被送出,造成無限等待。要一次喚醒全部等待者則用 pthread_cond_broadcast。

最經典的計數器範例

 pthread_mutex_t count_lock;
 pthread_cond_t count_nonzero;
 unsigned count;
 decrement_count () {
 pthread_mutex_lock (&count_lock);
 while(count==0)
 pthread_cond_wait( &count_nonzero, &count_lock);
 count=count -1;
 pthread_mutex_unlock (&count_lock);
 }
 increment_count(){
 pthread_mutex_lock(&count_lock);
 if(count==0)
 pthread_cond_signal(&count_nonzero);
 count=count+1;
 pthread_mutex_unlock(&count_lock);
 }

當 count 為 0,decrement 卡在 pthread_cond_wait 並自動解開 count_lock;此時 increment 呼叫 signal 改變條件變數,通知 decrement 停止阻塞。注意 decrement 用的是 while 迴圈,這正是正確寫法。

為什麼光有鎖不夠

共享資源往往不只要「沒人佔用」,還要「處於可用狀態」才能操作。例如某執行緒要從堆疊讀資料,但堆疊是空的,它就得等資料被壓入。這種同步不是互斥鎖能表達的,而正是條件變數的舞臺。

完整流程是:先鎖住互斥鎖 → 檢查共享資源狀態是否可用 → 不可用則等待條件變數(等待時原子地解鎖,讓別人有機會改變狀態,返回時又保證鎖是持有的)→ 另一個執行緒改變狀態後發出通知 → 被喚醒者重新搶鎖並再檢查一次。

雙執行緒協同範例

 #include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_mutex_t cond_mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_var=PTHREAD_COND_INITIALIZER;
void* function_cond1();
void* function_cond2();
int count=0;
#define COUNT_DONE 10
#define COUNT_HALT1 3
#define COUNT_HALT2 6
int main()
{
 pthread_t thread1,thread2;
 pthread_create(&thread1,NULL,function_cond1,NULL);
 pthread_create(&thread2,NULL,function_cond2,NULL);
 pthread_join(thread1,NULL);
 pthread_join(thread2,NULL);
 printf("Final count: %d\n",count);
 return 0;
}
void* function_cond1()
{
 for(;;)
 {
 pthread_mutex_lock(&cond_mutex);
 pthread_cond_wait(&cond_var,&cond_mutex);
 count++;
 printf("Counter value functionCount1: %d\n",count);
 pthread_mutex_unlock(&cond_mutex);
 if(count>=COUNT_DONE) return ;
 }
}
void* function_cond2()
{
 for(;;)
 {
 pthread_mutex_lock(&cond_mutex);
 if(count<COUNT_HALT1||count>COUNT_HALT2)
 {
 // 條件成立,發訊號喚醒等待中的 thread1
 pthread_cond_signal(&cond_var);
 }
 else
 {
 count++;
 printf("Counter value functionCount2: %d\n",count);
 }
 pthread_mutex_unlock(&cond_mutex);
 if(count>=COUNT_DONE) return ;
 }
}

POSIX 多執行緒:條件變數 pthread_cond_t 詳解

兩個執行緒同時運行。thread1 一開始就卡在 pthread_cond_wait;thread2 每次發現 count 落在 (COUNT_HALT1, COUNT_HALT2) 區間之外時,就呼叫 pthread_cond_signal 把 thread1 放進來加一。兩者就這樣接力把計數推到 COUNT_DONE。這個結構也解釋了為何等待必須寫在 while 迴圈裡:喚醒只是「可能」,條件仍需在鎖的保護下重新驗證。

Copyright © Linux教程網 All Rights Reserved