When I call pthread_exit
from main
, the program never gets to terminate. I expected the program to finish, since I was exiting the program's only thread, but it doesn't work. It seems hung.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int main(int argc, char *argv[])
{
printf("-one-\n");
pthread_exit(NULL);
printf("-two-\n");
}
Process Explorer shows that the (only) thread is in Wait:DelayExecution
state.
According to pthread_exit
documentation:
The process shall exit with an exit status of 0 after the last thread has been terminated. The behavior shall be as if the implementation called exit() with a zero argument at thread termination time.
I'm using Dev-C++ v4.9.9.2 and pthreads-win32 v2.8.0.0 (linking against libpthreadGC2.a
).
The library seems to be OK (for example, calling pthread_self
or pthread_create
from main
works fine).
Is there any reason for what I'm not supposed to call pthread_exit
from main
?
When testing on Linux (CentOS Linux release 7.2.1511 (Core)) I found that indeed the main program waits for "child" threads to continue. Also I was not able to pass out a return code from main, although it can be specified as argument for pthread_exit(), as Raul said above it always returns with exit code 0:
We also observed an error message when using Clang compiler (version 3.4.2) and sanitizer options:
Well its definately legal in the linux implementation of pthreads, see the notes section in pthreads_exit. It states
Further, a look at the source code here (torwads the end) shows that it roughly translates to _endthread or _endthreadex. The documentation here for those makes no mention of not calling it in the initial thread.
It's fine to use pthread_exit in main. When pthread_exit is used, the main thread will stop executing and will remain in zombie(defunct) status until all other threads exit.
If you are using pthread_exit in main thread, cannot get return status of other threads and cannot do clean-up for other threads (could be done using pthread_join(3)). Also, it's better to detach threads(pthread_detach(3)) so that thread resources are automatically released on thread termination. The shared resources will not be released until all threads exit.
Its ok to use when not allocating resources in the main thread, clean-up is not needed. Below code shows using pthread_exit in the main thread. The second printf in main is not printed as main thread exits after calling pthread_exit. Ps output shows the defunct main thread.
Output of the above code:
ps
output:Please check blog Tech Easy for more information on threads.
This completely legal and intended behavior. The whole process only ends when either all threads terminate or
exit
is called explicitly or implicitly.A normal return from
main
is equivalent to a call toexit
. If you endmain
withpthread_exit
your are saying explicitly that you want the other threads to continue.