线程分离属性
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <unistd.h>static void* thread_fun(void*arg)
{//pid_t pid;// pthread_detach(pthread_self()); // 使用这个 有概率 pthread_join 运行正常sleep(1);printf(" thread_fun \r\n");
}int main()
{pthread_t tid;pthread_attr_t attr;pthread_attr_init(&attr);pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); // PTHREAD_CREATE_JOINABLE// pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);if(pthread_create(&tid,&attr,thread_fun,NULL)){printf("create new thread failed\r\n");return -1;}// 销毁属性对象pthread_attr_destroy(&attr);// usleep(100000);if(pthread_join(tid,NULL)) // 等待子进程退出{printf("join thread failed \r\n");}else{printf("pthread_join success \r\n");}sleep(5);//pmap -x 3214 | grep stackreturn 0;
}
线程分离后,不需要使用pthread_join 来释放该线程资源 线程自身运行完会释放资源
默认线程是可连接 pthread_join会等待资源释放
pthread_detach(pthread_self()); // 使用这个 有概率 pthread_join 运行正常
gcc thread_detach.c -o thread_detach -lpthread