Reputation: 104
I wrote the following code:
#include <pthread.h>
#include <stdio.h>
void* sayHello (void *x){
printf ("Hello, this is %d\n", (int)pthread_self());
return NULL;
}
int main (){
pthread_t thread;
pthread_create (&thread, NULL, &sayHello, NULL);
printf("HERE\n");
return 0;
}
After compiling and running I saw 3 different types of outputs.
Of course I'm OK with the second option, but I don't understand why the 'sayHello' massege can be printed 0 or 2 times if I created only one thread?
Upvotes: 3
Views: 182
Reputation: 409136
You can't say when the thread starts to run, it might not start until
after you return from main
which means the process will end and the thread with it.
You have to wait for the thread to finish, with pthread_join
, before leaving main
.
The third case, with the message from the thread printed twice, might be because the thread executes, and the buffer is written to stdout
as part of the end-of-line flush, but then the thread is preempted before the flush is finished, and then the process exist which means all file streams (like stdout
) are flushed so the text is printed again.
Upvotes: 6
Reputation: 2219
your main
function only create a pthread, and let it run without waiting for it to finish.
When your main function return, Operating system will collect back all the resources assigned to the pprocess. However the newly created pthread might have not run.
That is why you only got HERE
.
your newly created thread finished before main
function return. Therefore you can see both the main thread, and the created thread's output.
This should be a bug in glibc
. Please refer to Unexpected output in a multithreaded program for details.
pthread_join
is needed after pthread_create
Upvotes: 4