Linux系統程式設計之執行緒條件變數

2021-10-08 20:45:56 字數 2503 閱讀 5006

#include

#include

#include

#include

pthread_cond_t cond=pthread_cond_initializer;

//初始化條件變數

pthread_mutex_t mutex=pthread_mutex_initializer;

//靜態初始化互斥鎖

struct msg //公共**區

;struct msg* head;

//定義頭節點

void

*produse

(void

* arg)

return

nullptr;}

void

*consumer

(void

* arg)

mp=head;

//將head賦值給結構體mp

head=mp-

>next;

//然後將其置為空

pthread_mutex_unlock

(&mutex)

;//解鎖

printf

("consumer*****=>>%d\n"

,mp-

>num)

;free

(mp)

;//釋放之前申請的記憶體空間

sleep

(rand()

%3);

//隨機睡眠方便觀察

}return

nullptr;}

intmain

(int argc,

char

const

*ar**)

輸出結果:

kali@kali:

~/code$ g++

1.cpp -lpthread

kali@kali:

~/code$ .

/a.out

produse:399

consumer==

====

>>

399produse:807

consumer==

====

>>

807produse:92

produse:956

consumer==

====

>>

956produse:347

produse:46

produse:212

consumer==

====

>>

212produse:705

consumer==

====

>>

705produse:255

consumer==

====

>>

255produse:127

consumer==

====

>>

127produse:211

produse:639

consumer==

====

>>

639produse:274

consumer==

====

>>

274produse:674

consumer==

====

>>

674produse:633

consumer==

====

>>

633produse:966

consumer==

====

>>

966produse:13

consumer==

====

>>

13produse:82

consumer==

====

>>

82produse:751

consumer==

====

>>

751produse:922

produse:713

consumer==

====

>>

713produse:925

consumer==

====

>>

925consumer==

====

>>

922produse:774

consumer==

====

>>

774produse:418

produse:107

produse:727

produse:73

consumer==

====

>>

73produse:134

produse:814

produse:493

produse:442

^ckali@kali:

~/code$

系統程式設計之執行緒

pthread t tid 建立執行緒號,多個執行緒可以用陣列來實現,如pthread t tid 3 函式原型 int pthread create pthread t tid,const pthread attr t restrict attr,void start rtn void void ...

Linux系統程式設計之執行緒 二 下

阻塞等待執行緒退出,獲取執行緒退出狀態 其作用,對應程序中的waitpid 函式 int pthread join pthread t thread,void retval 返回值 成功 0 失敗 錯誤號 引數 thread 執行緒id 注意 不是指標 retval 儲存執行緒結束狀態 對比記憶 程...

linux系統程式設計 執行緒

include int pthread create pthread t thread,const pthread attr t attr,void start routine void void arg include include include include include include...