Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detached Threads

Tags:

c

When we make Detached threads in main. and supose main exits... do the detached threads keep on going on or do they also exit just like our normal Joinable threads?

like image 584
user420878 Avatar asked Aug 15 '10 09:08

user420878


2 Answers

It depends entirely on how the main thread exits. If it exits using exit() or returning from main(), then the entire process is exited, and every thread is terminated.

However, if it uses pthread_exit() to terminate, then the process continues running.

like image 194
caf Avatar answered Sep 22 '22 15:09

caf


If this would be another thread then main, the other threads would continue. But the C99 standard says

If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function...

(All common platforms nowadays will return an int from main, in particular this is required by POSIX.)

And the POSIX page for exit states

These functions shall terminate the calling process...

So in summary a return from main terminates the whole program including all threads.

like image 36
Jens Gustedt Avatar answered Sep 22 '22 15:09

Jens Gustedt