我在同一个进程中有一个关于主线程和其他线程的问题.当主函数返回时,其他线程也退出?我有点困惑我我写了一些测试代码,像这样:
void* test1(void *arg)
{
unsigned int i = 0;
while (1){
i+=1;
}
return NULL;
}
void* test2(void *arg)
{
long double i = 1.0;
while (1){
i *= 1.1;
}
return NULL;
}
void startThread ( void * (*run)(void*),void *arg) {
pthread_t t;
pthread_attr_t attr;
if (pthread_attr_init(&attr) != 0
|| pthread_create(&t,&attr,run,arg) != 0
|| pthread_attr_destroy(&attr) != 0
|| pthread_detach(t) != 0) {
printf("Unable to launch a thread\n");
exit(1);
}
}
int main()
{
startThread(test1,NULL);
startThread(test2,NULL);
sleep(4);
printf("main thread return.\n");
return 0;
}
当“主线程返回”时.推出线程test1和test2也退出,有人可以告诉我为什么吗?
解决方法
当主线程返回时,它终止整个进程.这包括所有其他线程.当你打电话退出时也会发生同样的事情.
pthread_detach的目的是使它不需要与其他线程加入,以释放他们的资源.分离线程不会使它存在于过程终止之后,它仍将与所有其他线程一起销毁.