c++ - Linux C++ : Does a return from main() cause a multithreaded app to terminate?

标签 c++ linux multithreading process pthreads

这个问题似乎是重复的,但我找不到。如果我错过了之前的问题,我们深表歉意。

在我最有经验的 Java 中,如果您的 main() fork 一个线程并立即返回,该进程将继续运行,直到该进程中的所有(非守护进程)线程都已停止。

在 C++ 中,情况似乎并非如此——只要主线程返回,进程就会终止,而其他线程仍在运行。对于我当前的应用程序,可以通过应用 pthread_join() 轻松解决这个问题,但我想知道是什么原因导致了这种行为。这个编译器 (gcc) 是特定的、pthreads 特定的,还是在大多数/所有已实现 C++ 的平台之间共享的行为?这种行为是否可以在 pthreads 中配置(我已经在 pthread_attr_*() 函数中查看了 pthread api,但没有看到任何看起来相关的东西。)?

完全独立的问题,但是当你在这里时......一个人会使用 pthread_detatch() 做什么?

最佳答案

是的。在现代 linux 中(更重要的是 GNU libc 的更新版本)exit_group 是 main 返回时使用的系统调用,而不是普通的 exitexit_group描述如下:

This system call is equivalent to exit(2) except that it terminates not only the calling thread, but all threads in the calling process's thread group.

值得注意的是,当前的 c++ 标准未提及线程,因此此行为不是特定于 c++ 的,而是特定于您的特定实现的。也就是说,我亲眼看到的每个实现都会在主线程终止时终止所有线程。

编辑: Jonathan Leffler 的回答也值得注意,他指出 POSIX 标准确实指定了这种行为,因此对于使用 pthreads 进行线程处理的应用程序来说这当然是正常的。

编辑: 回答关于 pthread_detach 的跟进。如果您不加入非分离线程,基本上它被认为是资源泄漏。如果你有一个长时间运行的任务,你不需要“等待”,它只是“在它结束时结束”,那么你应该分离它,当它在没有连接的情况下终止时不会有资源泄漏。手册页说明如下:

The pthread_detach() function marks the thread identified by thread as detached. When a detached thread terminates, its resources are automatically released back to the system without the need for another thread to join with the terminated thread.

所以一个快速而肮脏的答案是:“当你不关心它何时结束时,分离它。如果另一个线程关心它何时结束并且必须等待它终止,那么不要。”

关于c++ - Linux C++ : Does a return from main() cause a multithreaded app to terminate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3305478/

相关文章:

Python 队列 block 超时不会超时 - 知道为什么吗?

java - 为大量外部 API 请求扩展软件/硬件?

c - 函数 ‘sched_setaffinity’ 的隐式声明

c++ - 此 C++ 代码如何返回 0,0,3

c++ - 返回指向私有(private)成员的指针的公共(public)方法的单元测试

c++ - 为什么按下 "Tab"键只会发出 QEvent::ShortcutOverride 事件?

linux - 设置iso存储库

c - 读取C中缓冲区的特定部分

c - 线程安全唯一事务ID

c++ - 如何在Qt中制作exe文件?