正常釋放
等待線程執行結束,和回收資源。
線程在函數執行結束以后,需要回收資源。
線程有兩種狀態joinable
和unjoinable
。
unjoinable
下,線程所使用的資源不會被釋放,直到joinable
。
pthread_join(pthread_t,void *)
使函數變為
joinable
第一個參數是線程id,第二個參數可以是函數的返回值,如果是NULL
表示我們不關心函數的返回值。如果需要返回值,需要先創建對應的結構體,然后傳入指針,讓函數填充。
程序將會在該語句出堵塞,直到線程執行完畢返回。即使有很多該函數也會依次執行。
int pthread_atfork(void (prepare)(void), void (parent)(void), void (*child)(void));
pthread_detach(pthread_t)
即使函數沒執行完也可以使用該函數制定線程的狀態
執行該函數后,線程中函數運行結束后直接釋放所消耗的資源。
異常釋放
線程異常中斷,被別的線程取消執行。
在POSIX線程API中提供了一個pthread_cleanup_push()/pthread_cleanup_pop()函數對用于自動釋放資源:
從pthread_cleanup_push()的調用點到pthread_cleanup_pop()之間的程序段中的終止動作(包括調用 pthread_exit()和取消點終止)都將執行pthread_cleanup_push()所指定的清理函數。
API定義如下:
void pthread_cleanup_push(void (*routine) (void *), void *arg)
void pthread_cleanup_pop(int execute)
pthread_cleanup_push()/pthread_cleanup_pop()采用先入后出的棧結構管理
void routine(void *arg)函數在調用pthread_cleanup_push()時壓入清理函數棧,多次對pthread_cleanup_push()的調用將在清理函數棧中形成一個函數鏈,在執行該函數鏈時按照壓棧的相反順序彈出。
execute參數表示執行到pthread_cleanup_pop()時是否在彈出清理函數的同時執行該函數,為0表示不執行,非0為執行
這個參數并不影響異常終止時清理函數的執行。
pthread_cleanup_push(pthread_mutex_unlock, (void *) &mut);
pthread_mutex_lock(&mut);
/* do some work */
pthread_mutex_unlock(&mut);
pthread_cleanup_pop(0);
未完。。。