1

I'm newbie in thread, I have the code below:

#include<pthread.h>
#include<stdio.h>
#include <stdlib.h>
#define NUM_THREADS 5
void *PrintHello (void *threadid ){
     long tid ;tid = (long) threadid ;
     printf ("Hello World! It’s me, thread#%ld !\n" , tid );
     pthread_exit(NULL);
}
int main (int argc ,char *argv[] ){
    pthread_t threads [NUM_THREADS] ;
    int rc ;
    long t ;
    for( t=0; t<NUM_THREADS;  t++){
        printf ("In main: creating thread %ld\n" , t );
        rc = pthread_create(&threads[t],NULL,PrintHello,(void *)t );
    }
    pthread_exit(NULL);
}

I compile and the output here:1 But when i delete the last line "pthread_exit(NULL)", the output is sometimes as same as the above which always prints enough 5 sub-threads, sometimes just prints 4 sub-thread from thread 0-3 for instace:2 Help me with this, please!

  • Your two linked images look the same to me, for what it's worth, but I think I understand the output you are describing. – pilcrow May 03 '21 at 19:51

1 Answers1

0

Omitting that pthread_exit call in main will cause main to implicitly return and terminate the process, including all running threads.

Now you have a race condition: will your five worker threads print their messages before main terminates the whole process? Sometimes yes, sometimes no, as you have observed.

If you keep the pthread_exit call in main, your program will instead terminate when the last running thread calls pthread_exit.

pilcrow
  • 56,591
  • 13
  • 94
  • 135
  • So i think your mean is the main pthread_exit's function seem as same as the pthread_join, both wait for the last sub-thread terminates. So what is exactly difference between them? – Phước Nguyễn Duy May 04 '21 at 05:42
  • No, `pthread_exit` terminates the calling thread whereas `pthread_join` waits for a single, specific and joinable thread to finish. They’re quite different. – pilcrow May 04 '21 at 10:59
  • Oh when I replace the main `pthread_exit` with `pthread_joid` in the new code(like above just replace the thread array with a single thread), it seem no difference. So I wonder what exactly each work? – Phước Nguyễn Duy May 04 '21 at 13:31
  • Perhaps you should ask a separate question about that... – pilcrow May 04 '21 at 13:43