Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do child threads exit when the parent thread terminates

Tags:

c++

windows

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 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?

For linux how should this case be?

like image 437
excray Avatar asked Jan 12 '11 08:01

excray


People also ask

Does child threads still execute after even if their parent thread dies or terminates?

Because if parent thread dies or terminates then child thread should also die or terminate. If you run those threads as daemon threads, when main thread finishes, your application will exit.

Can main thread exit before child?

Yes. "this gets printed before the system. out. println() in the child threads.

What happens to threads when process exits?

Threads are part of the process. If the process exits, they (along with all other process resources) cease to exist.

Can parent thread create child threads?

Thread CreationThe creating thread is the parent thread, and the created thread is a child thread. Note that any thread, including the main program which is run as a thread when it starts, can create child threads at any time.


2 Answers

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.

like image 145
Andy Johnson Avatar answered Oct 05 '22 16:10

Andy Johnson


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.

like image 44
Joey Avatar answered Oct 05 '22 15:10

Joey