pthread_detach函数
int pthread_detach(pthread_t thread);??? 成功:0;失敗:錯(cuò)誤號(hào)
作用:從狀態(tài)上實(shí)現(xiàn)線程分離,注意不是指該線程獨(dú)自占用地址空間。
線程分離狀態(tài):指定該狀態(tài),線程主動(dòng)與主控線程斷開關(guān)系。線程結(jié)束后(不會(huì)產(chǎn)生僵尸線程),其退出狀態(tài)不由其他線程獲取,而直接自己自動(dòng)釋放(自己清理掉PCB的殘留資源)。網(wǎng)絡(luò)、多線程服務(wù)器常用。
進(jìn)程若有該機(jī)制,將不會(huì)產(chǎn)生僵尸進(jìn)程。僵尸進(jìn)程的產(chǎn)生主要由于進(jìn)程死后,大部分資源被釋放,一點(diǎn)殘留資源仍存于系統(tǒng)中,導(dǎo)致內(nèi)核認(rèn)為該進(jìn)程仍存在。(注意進(jìn)程沒有這一機(jī)制)
也可使用 pthread_create函數(shù)參2(線程屬性)來設(shè)置線程分離。
一般情況下,線程終止后,其終止?fàn)顟B(tài)一直保留到其它線程調(diào)用pthread_join獲取它的狀態(tài)為止(或者進(jìn)程終止被回收了)。但是線程也可以被置為detach狀態(tài),這樣的線程一旦終止就立刻回收它占用的所有資源,而不保留終止?fàn)顟B(tài)。不能對(duì)一個(gè)已經(jīng)處于detach狀態(tài)的線程調(diào)用pthread_join,這樣的調(diào)用將返回EINVAL錯(cuò)誤(22號(hào)錯(cuò)誤)。也就是說,如果已經(jīng)對(duì)一個(gè)線程調(diào)用了pthread_detach就不能再調(diào)用pthread_join了。
//使用pthread_detach函數(shù)實(shí)現(xiàn)線程分離
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <pthread.h>void *tfn(void *arg) {int n = 3;while (n--) {printf("thread count %d\n", n);sleep(1);}//return (void *)1;pthread_exit((void *)1); }int main(void) {pthread_t tid;void *tret;int err;#if 0pthread_attr_t attr; /*通過線程屬性來設(shè)置游離態(tài)(分離態(tài))*/pthread_attr_init(&attr);pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);pthread_create(&tid, &attr, tfn, NULL);#elsepthread_create(&tid, NULL, tfn, NULL);pthread_detach(tid); //讓線程分離 ----自動(dòng)退出,無系統(tǒng)殘留資源#endifwhile (1) {err = pthread_join(tid, &tret);printf("-------------err= %d\n", err);if (err != 0)fprintf(stderr, "thread_join error: %s\n", strerror(err));elsefprintf(stderr, "thread exit code %d\n", (int)tret);sleep(1);}return 0; }[root@localhost 01_pthread_test]# ./pthrd_detach
-------------err= 22??? ???//可見錯(cuò)誤號(hào)是22
thread count 2
thread_join error: Invalid argument? //錯(cuò)誤號(hào)對(duì)應(yīng)的詳細(xì)解釋
thread count 1
-------------err= 22
thread_join error: Invalid argument
-------------err= 22
thread count 0
thread_join error: Invalid argument
-------------err= 22
thread_join error: Invalid argument
-------------err= 22
thread_join error: Invalid argument
分析:
總結(jié)
以上是生活随笔為你收集整理的pthread_detach函数的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 成都欢乐谷只蹦极也需要买门票么
- 下一篇: pthread_cancel、pthre