Asaf Kahlon
Asaf Kahlon

Reputation: 104

A strange result in a simple pthread code

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.

  1. Only "Here" was printed.
  2. "Here" and 1 'sayHello' message.
  3. "Here" and 2 'sayHello' messages.

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

Answers (2)

Some programmer dude
Some programmer dude

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

Kun Ling
Kun Ling

Reputation: 2219

For output 1:

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.

For output 2:

your newly created thread finished before main function return. Therefore you can see both the main thread, and the created thread's output.

For output 3

This should be a bug in glibc. Please refer to Unexpected output in a multithreaded program for details.

To make the program always has the same output

pthread_join is needed after pthread_create

Upvotes: 4

Related Questions