简体   繁体   English

为什么pthread_exit(0)挂起程序?

[英]Why does pthread_exit(0) hangs the program?

Running the following C code causes the program to hang, and does not respond to signals (including CTRL-C). 运行以下C代码将导致程序挂起,并且不响应信号(包括CTRL-C)。

int main()
{
    pthread_exit(0);
    return 0;
}

Any idea why? 知道为什么吗?

The behaviour is normal when other threads have been created and are running, but I would like to know if I always have to check that before using pthread_exit(0). 当其他线程已经创建并正在运行时,该行为是正常的,但是我想知道在使用pthread_exit(0)之前是否始终需要检查该线程。

EDIT: This is the complete code that hangs. 编辑:这是挂起的完整代码。 However, I was building with glib (-lglib-2.0). 但是,我正在使用glib(-lglib-2.0)进行构建。 Using simply cc -o foo foo.c works as expected. 仅使用cc -o foo foo.c即可按预期工作。

Your entire use case is described in the notes of the pthread_exit man page . pthread_exit手册页注释中描述了整个用例。 In your case, as you correctly edited your OP, glib started another thread. 在您的情况下,当您正确编辑OP时,glib启动了另一个线程。 You exited the main thread and the other thread kept running. 您退出了主线程,另一个线程保持运行状态。 You labeled this as a hang. 您将其标记为挂起。 In general, if you want to exit the application in full, just use exit or return from main() . 通常,如果要完全退出应用程序,只需使用exit或从main()返回。

Only when you need additional magic (rarely) like detached threads, use pthread_exit() on the main thread. 仅在需要额外的魔术(很少)(如分离线程pthread_exit() ,才应在主线程上使用pthread_exit()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM