- When the main thread exits - do we exit from all process?
As already explained here, when the main thread (or any thread) calls exit, or when the initial
invocation of main returns, the entire process exits. But the main
thread can exit with pthread_exit without affecting other threads.
- When one of the threads calls exit(1) - do we exit exit from all process?
Yes, we do.
- When one of the threads calls return 0 - do we exit exit from all
process?
No, we don't. We only return back from that thread.
From the link, A thread can terminate its execution in the following ways:
- By returning from its first (outermost) procedure, the threads start routine
- By calling pthread_exit(), supplying an exit status
- By termination with POSIX cancel functions
The void pthread_exit(void *status) is used terminate a thread in a
similar fashion the exit() for a process.
- When one of the threads calls return NULL - do we exit exit
from all process?
It's same as calling return 0
, as NULL is defined to be 0. So, same
answer as for the above question.
4b. *Is it different if the main thread calls it (return 0
or return NULL
) or another thread?
*
Yes, if main thread calls, refer answer to question 1 and if another
thread calls, refer answer to question 3.
In nutshell, if main
exits or returns, it makes the entire process to exit. To avoid this, pthread_exit
can be used which waits till the last thread terminates. If a thread calls exit()
, it makes the entire process to exit, and if it calls return NULL
or return 0
or pthread_exit
, only that particular thread exits.