gpt4 book ai didi

c - 主线程退出时,其他线程是否也退出?

转载 作者:太空狗 更新时间:2023-10-29 16:27:34 25 4
gpt4 key购买 nike

我对同一进程中的主线程和其他线程有疑问。当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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com