pthread_detach函数
pthread_join函数用于连接线程,阻塞等待某个线程结束,线程结束后回收线程资源,线程在创建后就在连接状态,只有可连接的函数才能被连接到。创建线程后,如果没有使用pthread_join,线程结束后资源无法回收,线程就会成为僵尸。 pthread_detach用于分离线程,分离后的线程会自己释放资源不会成为僵尸。
include <pthread.h>
#include <stdio.h>
#include <unistd.h>#define N 10void* thread_fun_0(void* arg) {for (int i = 0; i < N; ++i) {printf("thread_fun_0[%d]\n",i);sleep(1);}pthread_exit((void *)("thread_fun_0"));
}void* thread_fun_1(void* arg) {for (int i = 0; i < N; ++i) {printf("thread_fun_1[%d]\n",i);sleep(1);}pthread_exit((void *)("thread_fun_1"));
}
int main() {pthread_t tid_0, tid_1;printf("main beign\n");pthread_create(&tid_0, NULL, thread_fun_0, NULL);pthread_create(&tid_1, NULL, thread_fun_1, NULL);void *thread_fun_0_r;void *thread_fun_1_r;int result_0 = pthread_join(tid_0, &thread_fun_0_r);int result_1 = pthread_join(tid_1, &thread_fun_1_r);printf("result_0:%d,thread_fun_0_r:%s\n",result_0,(char*)thread_fun_0_r);printf("result_1:%d,thread_fun_1_r:%s\n",result_1,(char*)thread_fun_1_r);printf("main end\n");pthread_exit(NULL);
}
.在主线使用 pthread_join函数,获得了线程的返回结果。如果在线程中使用pthread_detach函数分离线程。如果分离后使用pthread_join函数就无效。
使用pthread_detach( thread_self() )与pthread_detach( tid_0);pthread_join就无法阻塞并且获取线程返回值,pthread_join函数返回值是22.即EINVAL,