Linux 多線程編程入門–線程函數解釋
來源:互聯網
上載者:User
建立線程:int pthread_create(pthread_t *restrict thread,
const pthread_attr_t *restrict attr,
void *(*start_routine)(void*), void *restrict arg);
參數: thread輸出線程id
attr 線程屬性, 預設NULL start_routine線程執行函數 arg線程執行參數
note:
函數成功返回0 否則返回錯誤碼標頭檔 pthread.h庫檔案 pthread
退出線程:int pthread_exit(void * value_ptr);
參數: value_ptr 線程傳回值指標
note: ptrhead_exit()
退出調用此函數的線程並釋放該線程佔用的資源標頭檔 pthread.h庫檔案 pthread
等待指定線程結束:int pthread_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來起到防止同時訪問或改變同一資料.
建立互斥:int pthread_mutex_init(pthread_mutex_t *restrict mutex,
const pthread_mutexattr_t *restrict attr);
參數: mutex輸出互斥id
attr 互斥屬性, 預設NULL
note:
函數成功返回0 否則返回錯誤碼標頭檔 pthread.h庫檔案 pthread
鎖住互斥:int pthread_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
解鎖互斥:
int
pthread_mutex_unlock(pthread_mutex_t *mutex);
參數:
mutex互斥id
note:
如果指定的互斥id已經被鎖住那麼對其解鎖標頭檔 pthread.h庫檔案 pthread
釋放互斥:
int
pthread_mutex_destroy(pthread_mutex_t *mutex);
參數:
mutex互斥id
note:
釋放指定的mutex佔用的資源標頭檔 pthread.h庫檔案 pthread