I was doing some multithreaded programming in Visual studio C++ using the calls beginthreadex, endthreadex.
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 fin开发者_运维知识库ishes 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?
For linux how should this case be?
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.
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.
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.
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 WaitForObject before you leave the program (we join the parent thread with the child thread).
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 Politely fro more info.
精彩评论