线程是可结合或分离的。一个可结合的线程能够被其他线程收回资源和杀死。相反,一个分离的线程是不能被其他线程收回或杀死的,它的存储器资源在它终止时由系统自动释放。
默认情况下,线程被创建为可结合的。
线程分离函数:int pthread_detach(pthread_t thread);
由于调用pthread_join后,如果该线程没有运行结束,调用者会被阻塞,但有些情况并不希望如此,所以可以在子线程中加入分离函数,将子线程的状态设置为分离的,这样在该线程运行结束后会自动释放所有资源。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* pthread_run()
{
pthread_detach(pthread_self());
printf("child function\n");
return NULL;
}
int main()
{
pthread_t tid;
int ret = pthread_create(&tid, NULL, pthread_run, NULL);
/*if(ret != 0)
{
perror("pthread_create");
return -1;
}*/
int tmp = 0;
sleep(1);
if(0 == pthread_join(tid, NULL))
{
printf("pthread wait success!\n");
ret = 0;
}
else
{
printf("pthread wait failed!\n");
ret = 1;
}
return ret;
}
在子线程运行完毕后,分离tid后,查看是否能够等待成功,若不能则说明分离成功。