linux 執行緒 條件變數

2021-08-15 09:10:43 字數 1699 閱讀 1571

與互斥鎖不同,條件變數是用來等待而不是用來上鎖的。條件變數用來自動阻塞乙個執行緒,直到某特殊情況發生為止。條件變數使我們可以睡眠等待某種條件出現。

條件變數是利用執行緒間共享的全域性變數進行同步的一種機制,

主要包括兩個動作:

乙個執行緒等待"條件變數的條件成立"而掛起;另乙個執行緒使"條件成立"(給出條件成立訊號)。

條件的檢測是在互斥鎖的保護下進行的。如果條件為假,乙個執行緒自動阻塞,並釋放等待狀態改變的互斥鎖。

pthread_cond_wait 原子呼叫: 等待條件變數, 解除鎖, 然後阻塞 

當 pthread_cond_wait 返回,則條件變數有訊號,同時上鎖

等待條件有兩種方式:

條件等待pthread_cond_wait()和計時等待pthread_cond_timedwait(), 

其中計時等待方式如果在給定時刻前條件沒有滿足,則返回etimeout

無論哪種等待方式,都必須和乙個互斥鎖配合,以防止多個執行緒同時請求pthread_cond_wait() 

(或pthread_cond_timedwait(),下同)的競爭條件(race condition)。

mutex互斥鎖必須是普通鎖(pthread_mutex_timed_np)或者適應鎖(pthread_mutex_adaptive_np), 

且在呼叫pthread_cond_wait()前必須由本執行緒加鎖(pthread_mutex_lock()),而在更新條件等待佇列以前, 

以與進入pthread_cond_wait()前的加鎖動作對應。

激發條件有兩種形式,pthread_cond_signal()啟用乙個等待該條件的執行緒,存在多個等待執行緒時按入隊順序啟用其中乙個; 

而pthread_cond_broadcast()則啟用所有等待執行緒(驚群)。

例子:

#include #include int icount = 0;

pthread_mutex_t mutex;

pthread_cond_t lock_cond;

void addfunc(int _inum)

}pth1_func(void * _pcbuffer)

}pth2_func(void * _pcbuffer)

}pth3_func(void * _pcbuffer)

pthread_mutex_unlock(&mutex);

}int main(int argc, char * argv [ ])

iret = pthread_create(&pthread2, null, (void *)&pth2_func, null);

if(iret)

iret = pthread_create(&pthread3, null, (void *)&pth3_func, null);

if(iret)

pthread_join(pthread1, null);

pthread_join(pthread2, null);

pthread_join(pthread3, null);

return 1;

}

當程式執行到函式pth3_func時,執行緒進行阻塞,並且解鎖,此時執行執行緒pth2_func和pth1_func,對全域性變數進行加一操作

,當全域性變數icount的值》=20時,傳送訊號,使執行緒pth3_func函式加鎖,繼續執行。

linux 執行緒 條件變數

條件變數本身不是鎖!但它也可以造成執行緒阻塞。通常與互斥鎖配合使用。給多執行緒提供乙個會合的場所 共享的資料 主要應用函式 pthread cond init函式 pthread cond destroy函式 pthread cond wait函式 pthread cond timedwait函式 ...

Linux執行緒同步 條件變數

執行緒間的同步還有乙個情況 程序a 需要等待乙個條件成立,才執行,當條件不成立時就阻塞等待 程序b 需要設定條件,當條件成立時,喚醒程序a.這裡我們就可以用到條件變數。條件變數變數也是出自posix執行緒標準,另一種執行緒同步機制,主要用來等待某個條件的發生,然後進行相應的操作,這樣可以消除多執行緒...

linux程式設計 執行緒 條件變數

條件變數通訊機制 基本原理 初始化條件變數 int pthread cond init pthread cond t restrict cond,const pthread condattr t restrict attr pthread cond t cond pthread cond initi...