Return from pthread
§How should I return from one pthread
1 | void *thread_function(void* arg) |
The pthread_exit
function from pthread library exits the calling thread as its name implies. If
one’s lazy, using return
works as well. Quoted from the above link:
Performing a return from the start function of any thread other than the main thread results in an implicit call to pthread_exit(), using the function’s return value as the thread’s exit status.
§How about the main thread?
main
thread is a bit special, which is the one runs main
function.
1 | int main(int argc, char **argv) |
Calling return
in the main thread would call exit(3), which will
terminate the whole process, meaning all the threads are killed. If we would like to wait for all the children
threads, we need to call pthread_join
explicitly, or call pthread_exit
.
To allow other threads to continue execution, the main thread should terminate by calling pthread_exit() rather than exit(3).