【发布时间】:2011-08-27 22:19:15
【问题描述】:
直到最近,我的印象是,如果您在生成线程后“分离”线程,即使在“主”线程终止后,该线程仍然存在。
但是一个小实验(如下所列)与我的看法相反。我预计即使在 main 终止后,分离的线程也会继续打印“从分离的线程说话”,但这似乎没有发生。应用程序显然终止了...
“主要”问题返回 0 后,“分离的”线程会死掉吗?
#include <pthread.h>
#include <stdio.h>
void *func(void *data)
{
while (1)
{
printf("Speaking from the detached thread...\n");
sleep(5);
}
pthread_exit(NULL);
}
int main()
{
pthread_t handle;
if (!pthread_create(&handle, NULL, func, NULL))
{
printf("Thread create successfully !!!\n");
if ( ! pthread_detach(handle) )
printf("Thread detached successfully !!!\n");
}
sleep(5);
printf("Main thread dying...\n");
return 0;
}
【问题讨论】:
-
在其他线程运行时退出主线程不是一个好主意;在任何情况下,从 main() 返回都会导致其他线程被杀死。
标签: c linux multithreading pthreads