Linux 條件變數

2021-10-25 21:59:28 字數 2965 閱讀 9877

與互斥鎖不同,條件變數是用來等待而不是用來上鎖的,乙個條件變數對應乙個等待佇列。條件變數是利用執行緒間共享的全域性變數進行同步的一種機制,主要包括兩個動作:乙個執行緒等待"條件變數的條件成立"而掛起;另乙個執行緒使"條件成立"(給出條件成立訊號)喚醒執行緒。

(1)pthread_cond_t cond=pthread_cond_initializer;

(2)int

pthread_cond_init

(pthread_cond_t *cond, pthread_condattr_t *cond_attr)

;

引數:cond為條件變數的位址, cond_attr用來設定條件變數的屬性,儘管posix標準中為條件變數定義了屬性,但在linuxthreads中沒有實現,因此cond_attr值通常為null,且被忽略。

返回值:成功返回0,失敗返回錯誤碼。

int

pthread_cond_destroy

(pthread_cond_t *cond)

;

只有在沒有執行緒在該條件變數上等待的時候才能登出這個條件變數,否則返回ebusy。因為linux實現的條件變數沒有分配什麼資源,所以登出動作只包括檢查是否有等待執行緒。

int

pthread_cond_wait

(pthread_cond_t *cond,pthread_mutex_t *mutex)

;

mutex.

lock()

;while

(判斷「條件」是否成立)

修改」條件「

mutext.

unlock()

;pthread_cond_signal 喚醒

pthread_cond_wait(cond, mutex)要完成的功能是,(1)將執行緒加入cond對應的等待佇列。(2) 釋放mutex鎖。(3)當執行緒被喚醒後還在pthread_cond_wait()體內,然後繼續加mutex加鎖,獲得鎖資源。需要注意的是(1)和 (2)是原子操作,所以不用在意他們的先後順序。當完成pthread_cond_wait操作後拿到鎖資源後為什麼還要判斷「條件」,因為可能有多個執行緒競爭鎖資源乙個執行緒拿到鎖資源後對「條件」改變,其他執行緒拿到做資源應該再次判斷是否等待。所以需要迴圈判斷。

int

pthread_cond_signal

(pthread_cond_t *cptr)

;int pthread_cond_broadcast (pthread_cond_t * cptr)

;//成功返回0,失敗返回錯誤碼.

喚醒條件有兩種形式,pthread_cond_signal()喚醒乙個等待該條件的執行緒,存在多個等待執行緒時按入隊順序喚醒其中乙個;而pthread_cond_broadcast()則喚醒所有等待執行緒。

生產者消費者模型是指,有一塊緩衝區,緩衝區有大小為 capacity。有多個生產者向緩衝區裡邊放資料,多個消費者從緩衝區裡邊取資料。

分析:(1)緩衝區滿,不能放資料。(2)緩衝區空不能取資料 (3)緩衝區同時只能有乙個消費者取,或者乙個生產者放。

實現如下:

#include

#include

#include

#include

using

namespace std;

#define max_queue 5

static

int i =0;

class

blockqueue

~blockqueue()

bool

push

(int date)

_queue.

push

(date)

;pthread_mutex_unlock

(&_mutex)

;pthread_cond_signal

(&_cond_consumer)

;return

true;}

bool

pop(

int* data)

//不滿足等待條件

*data = _queue.

front()

;//出佇列

//sleep(1);

_queue.

pop();

pthread_mutex_unlock

(&_mutex)

;//操作完臨界資源後解鎖

pthread_cond_signal

(&_cond_product)

;//喚醒生產者執行緒

return

true;}

private

: pthread_cond_t _cond_product;

pthread_cond_t _cond_consumer;

pthread_mutex_t _mutex;

queue<

int> _queue;

int _capacity;};

void

*thr_product

(void

* grm)

return

null;}

void

*thr_consumer

(void

* grm)

return

null;}

intmain()

}for

(int i =

0; i <

4; i++)}

pthread_join

(pro_tid[0]

,null);

pthread_join

(con_tid[0]

,null);

return0;

}

linux條件變數

linux條件變數 條件變數 條件變數是利用執行緒間共享是全域性變數進行同步的一種機制。條件變數巨集觀上類似if語句,符合條件就能執行某段程式,否則只能等待條件成立。一 函式 pthread cond init函式 初始化條件變數 pthread cond wait函式 基於條件變數阻塞,無條件等待...

Linux 條件變數

當乙個執行緒互斥地訪問某個變數時,它可能發現在其它執行緒改變狀態之前,它什麼也做不了。例如 乙個執行緒訪問佇列時,發現隊列為空,它只能等待,直到其它執行緒將乙個節點新增到佇列中。類似這種情況就需要用到條件變數。同步概念與競態條件 同步 在保證資料安全的前提下,讓執行緒能夠按照某種特定的順序訪問臨界資...

Linux 條件變數

條件變數 1.問題 某些情況下,某些執行緒有這個需求 僅當滿足某個特定條件時,才執行對應操作 如果該條件不滿足,就阻塞該執行緒,一直等到對應的條件滿足才繼續執行。解決方案 當條件滿足時,使用訊號量喚醒對應執行緒,當條件不滿足時,使用訊號量阻塞對應執行緒。並用互斥量 互斥鎖 來保護對該條件的訪問。li...