views:

89

answers:

2

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?

+1  A: 

Well its definately legal in the linux implementation of pthreads, see the notes section in pthreads_exit. It states

To allow other threads to continue execution, the main thread should terminate by calling pthread_exit() rather than exit(3).

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.

torak
Then I guess it should be legal in the win32 implementation (http://sourceware.org/pthreads-win32/bugs.html) too. I've been looking for a known bug that explains this behavior, but I couldn't find it.In my opinion, either this is a buggy behavior or there's an actual reason I am not supposed to call `pthread_exit` on `pthreads_win32`. Can anybody confirm any of these hypothesis?
@matasierra: I've added some more detail to the answer aboce. Also, what is main actually executing?
torak
The first `printf` is actually printed out, but the second one is not (as expected). The problem is that the program will not terminate. It simply gets kind of _frozen_.
I finally found the problem. I think it was some kind of malware on my operating system. I've just cleaned it up with an antispyware tool and now it works as expected. Oh, my... I feel really stupid.@torak I'm going to accept your answer. Thanks for your help!
+2  A: 

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 to exit. If you end main with pthread_exit your are saying explicitly that you want the other threads to continue.

Jens Gustedt