Strange result in 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.

  • Only "Here" is printed.
  • "Here" and the message "sayHello".
  • "Here" and 2 "sayHello" messages.

Of course I'm fine with the second option, but I don't understand why the "sayHello" massege can be printed 0 or 2 times if I only created one thread?

+3


source to share


2 answers


For output 1:

your function main

only creates pthread and lets you run it without waiting for it to complete.

When your main function returns, the operating system will return all resources assigned by pprocess. The newly created pthread, however, may not have worked.

That's why you got it HERE

.

For pin 2:



your newly created thread finished before the function returns main

. Therefore, you can see both the main thread and the created thread.

For exit 3

This should be a bug in glibc

. See Unexpected output in a multithreaded program for details .

So that the program always has the same output

pthread_join

required after pthread_create

+4


source


You can't tell when a thread will start, it may not start until after returning from main

, which means the process will end and the thread with it.

You need to wait for the flow to end pthread_join

before leaving main

.



The third case, with a message from the stream printed twice, could be caused by the stream being executed and the buffer is being written to stdout

as part of the end of the line, but then the stream is previously flushed out, the flash is finished, and then there is a process that means all streams of files (for example , stdout

) are cleared so that the text is printed again.

+6


source







All Articles