Warm tip: This article is reproduced from serverfault.com, please click

why the order of my output doesn't change even if i change my pthread_join() place

发布于 2020-11-28 19:07:54

why do I get the same output order when pthread_join( thread3, NULL); comes before pthread_join( thread1, NULL); and when: pthread_join( thread1, NULL); comes before pthread_join( thread3, NULL);

I know that pthread_join() waits for the thread to terminate and it worked on thread 2 but why it doesn't work here like I waited for thread 3 to terminate but it still terminates after thread 1 terminate.

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void * print_message_function( void *ptr );
void * do_something_else(  );
void * a_new_function();


int main()
{
     pthread_t thread1, thread2,thread3,thread4;

     char *message1 = "Thread 1   is running ";
     char *message2 = "Thread 2";
     int  iret1, iret2,iret3;

     void * (*f_ptr)();
     f_ptr = do_something_else; 

    

    /* Create independent threads each of which will execute function */

          iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);



          iret2 = pthread_create( &thread2, NULL, f_ptr/*do_something_else*/, NULL);

              pthread_join( thread2, NULL); 
     

        
          iret3 = pthread_create( &thread3, NULL,a_new_function , NULL);
         
     pthread_join( thread3, NULL); //--------------here-------------------------------

    pthread_join( thread1, NULL); //---------------here-------------------------------
   
     return 0;
}

void * print_message_function( void *ptr )
{
    int i;     
   
    for(int i=0; i < 1; i++)
       printf("%s \n", (char *)ptr);
}
void * a_new_function(){

int a;
int b;
int c;
a=5;b=7;
c=b+a;
printf ("the value of c =%d\n",c);

return 0;
}
void * do_something_else(  )
{
    int i;     
    
    for(int i=0; i < 1;  i++)
       printf("%s \n", "this is do_something_else function");
}

the output in both ways is:

**this is do_something_else function

Thread 1 is running

the value of c =12**

Questioner
sayo
Viewed
0
mevets 2020-11-29 03:38:54

Pthread_join does not affect the scheduling of the thread that you are joining with; really it is just a way to cleanup resources and retrieve exit status. In your example, the only dependency is that thread 2 will complete before thread 3, since you do not create thread 3 until you have joined thread 2.

This has no effect on thread 1; and the order of the final joins is irrelevant.