C++ 父线程终止时子线程是否退出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4666628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Do child threads exit when the parent thread terminates
提问by excray
I was doing some multithreaded programming in Visual studio C++ using the calls beginthreadex, endthreadex.
我正在使用调用 beginthreadex、endthreadex 在 Visual Studio C++ 中进行一些多线程编程。
I create a child thread thread1. The child thread runs on a function which never exits as it has an infinite loop. Now if the parent thread terminates with error or finishes successfully, does the child thread also exit? My doubt is - is there any situation where the child thread is alive even after the main program exits?
我创建了一个子线程thread1。子线程运行在一个永远不会退出的函数上,因为它有一个无限循环。现在,如果父线程因错误终止或成功完成,子线程是否也退出?我的疑问是 - 是否存在即使在主程序退出后子线程还活着的情况?
For linux how should this case be?
对于linux,这种情况应该如何?
回答by Andy Johnson
There is no parent/child relationship between threads. If thread A creates thread B and then thread A terminates, then thread B will continue to execute.
线程之间没有父/子关系。如果线程 A 创建线程 B,然后线程 A 终止,则线程 B 将继续执行。
The exception to this is when the main thread (that is, the thread that runs the main()
function) terminates. When this happens, the process terminates and all other threads stop.
例外情况是主线程(即运行该main()
函数的线程)终止时。发生这种情况时,进程终止,所有其他线程停止。
回答by Joey
Since C and C++ mandate that returning from the main
function kills all running threads, yes, the process should be gone. And since that behavior is done by the runtime the situation should be the same on Linux.
由于 C 和 C++要求从main
函数返回杀死所有正在运行的线程,是的,进程应该消失。由于该行为是由运行时完成的,Linux 上的情况应该相同。
回答by Javier Loureiro
As soon as your process die, all the resources are being released (memory, files and threads)
一旦你的进程死了,所有的资源都会被释放(内存、文件和线程)
The correct way to do this: when you call beginthread, keep the returned handle in the parent thread, and call WaitForObjectbefore you leave the program (we jointhe parent thread with the child thread).
正确的方法来做到这一点:当你打电话beginthread,保持父线程返回的句柄,并调用WaitForObject你离开程序(我们之前加入与子线程父线程)。
The parent thread will block until the child thread finish. If your child thread has a infinite loop, you could define an "interruption point" , and check if you should leave. For example, using a shared boolean variable. Check Interrupt Politelyfro more info.
父线程将阻塞,直到子线程完成。如果您的子线程有无限循环,您可以定义一个“中断点”,并检查您是否应该离开。例如,使用共享布尔变量。礼貌地检查中断以获取更多信息。