问题描述
我对同一进程中的主线程和其他线程有疑问.当main函数返回时,其他线程也退出吗?我对此感到困惑.
I have a problem about main threads and other threads in the same process. When the main function returns, do the other threads exit too? I am confused about this.
考虑以下测试代码:
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也退出,谁能告诉我为什么?
When the "main thread return." prints out, thread test1 and test2 also exit, can anyone tell me why?
推荐答案
当主线程返回时(即,您从main
函数返回),它将终止整个过程.这包括所有其他线程.当您调用exit
时,也会发生同样的事情.您可以通过调用pthread_exit
来避免这种情况.
When the main thread returns (i.e., you return from the main
function), it terminates the entire process. This includes all other threads. The same thing happens when you call exit
. You can avoid this by calling pthread_exit
.
pthread_detach
的目的是使它生效,因此您无需为了释放其资源而与其他线程联接.分离线程并不意味着它在进程终止后就不存在,它仍将与所有其他线程一起被破坏.
The purpose of pthread_detach
is to make it so you don't need to join with other threads in order to release their resources. Detaching a thread does not make it exist past process termination, it will still be destroyed along with all the other threads.
这篇关于当主线程退出时,其他线程也退出吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!