正常釋放
等待線程執(zhí)行結(jié)束县袱,和回收資源浑娜。
線程在函數(shù)執(zhí)行結(jié)束以后,需要回收資源式散。
線程有兩種狀態(tài)joinable
和unjoinable
筋遭。
unjoinable
下,線程所使用的資源不會被釋放暴拄,直到joinable
漓滔。
pthread_join(pthread_t,void *)
使函數(shù)變?yōu)?code>joinable
第一個參數(shù)是線程id,第二個參數(shù)可以是函數(shù)的返回值乖篷,如果是NULL
表示我們不關心函數(shù)的返回值响驴。如果需要返回值,需要先創(chuàng)建對應的結(jié)構(gòu)體撕蔼,然后傳入指針豁鲤,讓函數(shù)填充。
程序?qū)谠撜Z句出堵塞鲸沮,直到線程執(zhí)行完畢返回琳骡。即使有很多該函數(shù)也會依次執(zhí)行。
int pthread_atfork(void (prepare)(void), void (parent)(void), void (*child)(void));
pthread_detach(pthread_t)
即使函數(shù)沒執(zhí)行完也可以使用該函數(shù)制定線程的狀態(tài)
執(zhí)行該函數(shù)后讼溺,線程中函數(shù)運行結(jié)束后直接釋放所消耗的資源楣号。
異常釋放
線程異常中斷,被別的線程取消執(zhí)行肾胯。
在POSIX線程API中提供了一個pthread_cleanup_push()/pthread_cleanup_pop()函數(shù)對用于自動釋放資源:
從pthread_cleanup_push()的調(diào)用點到pthread_cleanup_pop()之間的程序段中的終止動作(包括調(diào)用 pthread_exit()和取消點終止)都將執(zhí)行pthread_cleanup_push()所指定的清理函數(shù)竖席。
API定義如下:
void pthread_cleanup_push(void (*routine) (void *), void *arg)
void pthread_cleanup_pop(int execute)
pthread_cleanup_push()/pthread_cleanup_pop()采用先入后出的棧結(jié)構(gòu)管理
void routine(void *arg)函數(shù)在調(diào)用pthread_cleanup_push()時壓入清理函數(shù)棧,多次對pthread_cleanup_push()的調(diào)用將在清理函數(shù)棧中形成一個函數(shù)鏈敬肚,在執(zhí)行該函數(shù)鏈時按照壓棧的相反順序彈出毕荐。
execute參數(shù)表示執(zhí)行到pthread_cleanup_pop()時是否在彈出清理函數(shù)的同時執(zhí)行該函數(shù),為0表示不執(zhí)行艳馒,非0為執(zhí)行
這個參數(shù)并不影響異常終止時清理函數(shù)的執(zhí)行憎亚。
pthread_cleanup_push(pthread_mutex_unlock, (void *) &mut);
pthread_mutex_lock(&mut);
/* do some work */
pthread_mutex_unlock(&mut);
pthread_cleanup_pop(0);
未完员寇。。第美。