以下举例代码pthread_detach函数通过另外两种方式回收对应线程结束的资源。
#include <stdio.h>
#include <pthread.h>
void *ptha_func(void * arg){
printf("ptha_func.....\n");
return NULL;
}
void *pthb_func(void * arg){
printf("pthb_func.....\n");
//pthread_self()函数获取当前线程id号,
//pthread_detach()函数等待当前线程id号对应线程结束,回收线程资源。
pthread_detach(pthread_self());
return NULL;
}
void *pthc_func(void * arg){
printf("pthc_func.....\n");
return NULL;
}
int main(void){
pthread_t ptida,ptidb,ptidc;
pthread_create(&ptida,NULL,ptha_func,NULL);
pthread_create(&ptidb,NULL,pthb_func,NULL);
pthread_create(&ptidc,NULL,pthc_func,NULL);
//将ptidc线程号设置为detached state状态
pthread_detach(ptidc);
printf("ptida pthread_join return value:%d\n",\
pthread_join(ptida,NULL));
printf("ptidb pthread_join return value:%d\n",\
pthread_join(ptidb,NULL));
printf("ptidc pthread_join return value:%d\n",\
pthread_join(ptidc,NULL));
return 0;
}
执行结果:
pthread$gcc pth_detach_other.c -lpthread
pthread$./a.out
ptha_func.....
pthb_func.....
pthc_func.....
ptida pthread_join return value:0
ptidb pthread_join return value:22
ptidc pthread_join return value:22
通过上述执行结果可以看出:
线程ptida执行结束后;由pthread_join函数回收线程资源。
线程ptidb和ptidc执行结束后;由pthread_detach函数回收线程资源。