32

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?

Nate Kohl
  • 35,264
  • 10
  • 43
  • 55
excray
  • 2,738
  • 4
  • 33
  • 49

3 Answers3

62

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.

Andy Johnson
  • 7,938
  • 4
  • 33
  • 50
  • 12
    Two exceptions. If *any* thread calls `exit`, then *all* threads terminate. – EML Oct 07 '16 at 15:46
  • 5
    I would also like to add that if `main` exists without calling `detach` on the running thread, you will have an exception thrown. – Everyone Mar 09 '17 at 10:30
10

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.

Joey
  • 344,408
  • 85
  • 689
  • 683
  • The link you provided does not say anything about a language requirement of *killing* (!) all threads. It only cites a requirement that returning from main is equivalent to calling exit(). – Florian Winter Jul 13 '16 at 08:22
  • The link don't work now. Can you provide a newer one – user2618142 Jun 13 '20 at 14:38
2

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.

Javier Loureiro
  • 354
  • 2
  • 12
  • Your case is fine when the program normally terminates, that is it reaches end of main(). But there are many places in the primary or parent thread that call exit(). So would exit() kill all threads? – excray Jan 12 '11 at 09:47
  • @user97642 If the main thread exits then all other threads stop – Andy Johnson Jan 12 '11 at 09:51
  • 3
    Be aware that infinite waits on semaphores, handles etc can cause your process to become a zombie in both Windows and Linux. Otherwise it's as the others say; when the main thread dies, all others are killed. – JimR Jan 12 '11 at 10:43