Possible Duplicate:
Understanding pthread_detach
The following code is creating a single thread which prints “new thread” .
#include<stdio.h>
#include<pthread.h>
void *thr_fn(void *arg)
{
printf("New thread\n");
sleep(5);
return (void *)1;
}
int main()
{
pthread_t pid;
void *t;
pthread_create(&pid,NULL,thr_fn,NULL);
printf("main thread\n");
exit(0);
}
The output can be any of these:
1.main thread
New thread
2.main thread
3.main thread
New thread
New thread
First and second are convincing . But can anybody explain the reason behind the third optional output.
I’m quite sure, that your program does not create two threads 😉
Most likely you see the effects of a race-condition on
stdoutbetween your new thread and the main thread.exitflushes and closes all streams. This might happen non-atomically and in parallel to the other thread writing into the same stream buffer and flushing that also to the file descriptor.