linux多執行緒 條件變數

2022-08-31 18:06:11 字數 861 閱讀 1575

**

#include

#include

#include

pthread_mutex_t mutex = pthread_mutex_initializer;/*初始化互斥鎖*/

pthread_cond_t cond = pthread_cond_initializer;/*初始化條件變數*/

void *thread1(void *);

void *thread2(void *);

int i=1;

int main(void)

void *thread1(void *junk)

pthread_mutex_unlock(&mutex);/*解鎖互斥量*/

printf("thread1: unlock %d/n/n", __line__);

sleep(1);}}

void *thread2(void *junk)

pthread_mutex_unlock(&mutex);

printf("thread2: unlock %d/n/n", __line__);

sleep(1);}}

編譯:[x61@horizon threads]$ gcc thread_cond.c -lpthread -o tcd

以下是程式執行結果:

這裡的兩個關鍵函式就在pthread_cond_wait和pthread_cond_signal函式。

本例中:

執行緒一先執行,獲得mutex鎖,列印,然後釋放mutex鎖,然後阻塞自己1秒。執行緒二此時和執行緒一應該是併發的執行

不過此時執行緒二並沒有立即得到執行

Linux多執行緒 條件變數

在多執行緒程式設計中僅使用互斥鎖來完成互斥是不夠用的,如以下情形 假設有兩個執行緒 t1 和 t2,需要這個兩個執行緒迴圈對乙個共享變數 sum 進行自增操作,那麼 t1 和 t2 只需要使用互斥量即可保證操作正確完成,執行緒執行 如所示 pthread mutex t sumlock pthrea...

Linux多執行緒程式設計 條件變數

include int pthread cond init pthread cond t cv,const pthread condattr t cattr 返回值 函式成功返回0 任何其他返回值都表示錯誤初始化乙個條件變數。當引數cattr為空指標時,函式建立的是乙個預設的條件變數。否則條件變數的...

條件變數 多執行緒

最近看 unix環境高階程式設計 多執行緒同步,看到他舉例說條件變數pthread cond t怎麼用,愣是沒有看懂,只好在網上找了份 跑了跑,才弄明白 cpp view plain copy include include include pthread mutex t mutex pthread...