在多線程同步中,pthread_cond_wait() 是等待條件變量的標準方式。典型用法如下:
pthread_mutex_lock(&mtx);
while (head != NULL) {
pthread_cond_wait(&cond, &mtx);
}
// 條件滿足,執行邏輯...
pthread_mutex_unlock(&mtx);
pthread_cond_wait 時,會自動釋放互斥鎖並進入等待狀態,這兩步是原子的。signal 或 broadcast)後,等待線程被喚醒,但必須重新獲得互斥鎖才能繼續執行。while (head != NULL) 確保線程喚醒後重新檢查條件。若條件不滿足,再次釋放鎖並進入等待。這樣能同時應對:
struct xxx* head; // 全局共享變量
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static void* thread_func(void* arg) {
pthread_mutex_lock(&mtx);
while (head != NULL) {
pthread_cond_wait(&cond, &mtx);
}
// head == NULL 時的處理邏輯
pthread_mutex_unlock(&mtx);
return NULL;
}
注意:此處的「信號」指線程間的條件變量通知機制,非 Unix 信號。