- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我对同一进程中的主线程和其他线程有疑问。当main函数返回时,其他线程是否也退出?我对此感到困惑。
考虑以下测试代码:
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_join()
在每个新线程上,通知调用线程在子线程上等待,暂停执行 - 并进程退出 - 直到这些线程终止。
调用 pthread_detach
在创建的线程上不会在进程退出后保留它们。来自 Linux man page :
The detached attribute merely determines the behavior of the system when the thread terminates; it does not prevent the thread from being terminated if the process terminates using exit(3) (or equivalently, if the main thread returns).
您有时会看到 pthread_exit
在 main
使用而不是显式 pthread_join
调用,意图是退出 main
这样就会让其他线程继续运行。事实上,linux man page明确指出:
To allow other threads to continue execution, the main thread should terminate by calling pthread_exit() rather than exit(3).
但我不知道这是否是所有平台上的预期行为,我一直坚持使用 pthread_join
.
pthread_join
需要 pthread_t
对于目标线程,因此您的代码需要稍微更改,因为您需要在调用 pthread_join
之前创建两个线程等待他们两个。所以你不能在startThread
中调用它.您需要返回 pthread_t
, 或传递指向 pthread_t
的指针给你的startThread
功能。
关于c - 主线程退出时,其他线程是否也退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11875956/
有人可以向我澄清主线 DHT 规范中的声明吗? Upon inserting the first node into its routing table and when starting up th
我正在尝试使用 USB 小工具驱动程序使嵌入式设备作为 MTP 设备工作。 我知道 Android 从大容量存储设备切换到 MTP 设备已经有一段时间了,并且找到了 source code for M
我是一名优秀的程序员,十分优秀!