Linux 多執行緒程式設計入門 執行緒函式解釋

2021-08-24 18:32:14 字數 3408 閱讀 9230

建立執行緒:

intpthread_create(pthread_t*restrictthread,

const

pthread_attr_t*restrictattr,

void

*(*start_routine)(

void

*),void

*restrictarg);

引數:

thread

輸出執行緒id

attr

執行緒屬性, 預設null

start_routine

執行緒執行函式

arg 執行緒執行引數

note:函式成功返回0 否則返回錯誤碼

標頭檔案 pthread.h

庫檔案 pthread

退出執行緒:

intpthread_exit(

void

* value_ptr);

引數:

value_ptr

執行緒返回值指標

note: ptrhead_exit()退出呼叫此函式的執行緒並釋放該執行緒占用的資源

標頭檔案 pthread.h

庫檔案 pthread

等待指定執行緒結束:

intpthread_join(pthread_t thread,

void

**value_ptr);

引數:

thread

乙個有效的執行緒id

value_ptr

接收執行緒返回值的指標

note:呼叫此函式的執行緒在指定的執行緒退出前將處於掛起狀態或出現錯誤而直接返回

如果value_ptr非null則value_ptr指向執行緒返回值的指標

函式成功後指定的執行緒使用的資源將被釋放

標頭檔案 pthread.h

庫檔案 pthread

獲取當前執行緒id:

pthread_t pthread_self(

void

); 引數:

note:返回當前函式的id

標頭檔案 pthread.h

庫檔案 pthread

互斥:

說到多執行緒,最關心的就是資料訪問

/ 改變的同步問題。

windows

下有臨界區和訊號事件等手段來防止多個執行緒同時讀

/ 寫同乙個資料,那麼

linux

呢? 多執行緒變成時多使用互斥

pthread_mutex_t

來起到防止同時訪問或改變同一資料

.

建立互斥:

intpthread_mutex_init(pthread_mutex_t*restrictmutex,

const

pthread_mutexattr_t*restrictattr);

引數:

mutex

輸出互斥id

attr

互斥屬性, 預設null

note:函式成功返回0 否則返回錯誤碼

標頭檔案 pthread.h

庫檔案 pthread

鎖住互斥:

intpthread_mutex_lock(pthread_mutex_t*mutex);

引數:

mutex

互斥id

note:如果指定的互斥id已經被鎖住那麼呼叫執行緒在互斥id完全解鎖前將

一直處於掛起狀態,否則將鎖住互斥體

標頭檔案 pthread.h

庫檔案 pthread

int pthread_mutex_trylock(pthread_mutex_t*mutex);

引數:

mutex

互斥id

note:如果指定的互斥id已經被鎖住那麼將直接返回乙個錯誤,通過判斷

此錯誤來進行不同的處理

標頭檔案 pthread.h

庫檔案 pthread

解鎖互斥:

intpthread_mutex_unlock(pthread_mutex_t*mutex);

引數:

mutex

互斥id

note:如果指定的互斥id已經被鎖住那麼對其解鎖

標頭檔案 pthread.h

庫檔案 pthread

釋放互斥:

intpthread_mutex_destroy(pthread_mutex_t*mutex);

引數:

mutex

互斥id

note:釋放指定的mutex占用的資源

標頭檔案 pthread.h

庫檔案 pthread

Linux 多執行緒程式設計入門

建立執行緒 intpthread create pthread t restrict thread,const pthread attr t restrict attr,void start routine void void restrict arg 引數 thread 輸出執行緒id attr ...

Linux多執行緒 pthread exit函式

執行緒的終止可以呼叫pthread exit函式來結束。也就是說,乙個執行緒可以隱式的退出,也可以顯式的呼叫pthread exit函式來退出。pthread exit函式唯一的引數value ptr是函式的返回 include void pthread exit void retval threa...

Linux 多執行緒程式設計入門 執行緒函式解釋

建立執行緒 intpthread create pthread t restrict thread,const pthread attr t restrict attr,void start routine void void restrict arg 引數 thread 輸出執行緒id attr ...