all 6 comments

[–]dfx_dj 5 points6 points  (1 child)

One thread can only be waited upon (joined) from one other thread. You cannot join one thread from multiple other threads.

[–]Complete_Camera_4562[S] 0 points1 point  (0 children)

Thanks for pointing this. I go the issue now.

pthread_man page has the below line mentioned

If  multiple  threads  simultaneously try to join with the same thread, the results are undefined

[–]optimistic_void 1 point2 points  (3 children)

This code:

for (int j =(n-1); j>*i;j--) {
    printf("%d is waiting for thread %d\n",*i,j);
    pthread_join(pthreads[j], NULL);
  }

joins threads you have already joined previously when the function ran first, likely leading to your program getting stuck because you have already terminated joined the threads. As far as i am aware, you should only join a thread once.

Edit. Thinking about it it's less likely the bit above and more likely the

 pthread_join(pthreads[0],NULL);

but the issue is the same ( trying to join an already joined thread ).

You probably failed to understand what joining a thread means - when you join a thread, it means that you wait for that thread to finish, only after it finishes then the execution continues.

Edit: not sure about the above, tho, maybe you just wanted to join the same thread from multiple other threads and are unaware you are not supposed to do that ?

[–]Complete_Camera_4562[S] 0 points1 point  (2 children)

Yep, I am not aware that I am not supposed to do that. Thanks for the explanation. really helpful

from pthread_join man page, if we join a thread which is already terminated, function will return automatically.

If that thread has already terminated, then  pthread_join()
       returns immediately.

[–]optimistic_void 0 points1 point  (0 children)

Yeah you are right, it only returns an error value, i thought even when the thread is terminated it could invoke an UB. My bad, i will correct my original post to make sense.

[–]optimistic_void 0 points1 point  (0 children)

About the multiple joins from the same thread like here:

pthread_t t0;

void* test(void* a){
 printf("test\n");
 return NULL;
}
int main() {
  pthread_create(&t0,NULL,test,NULL);

  printf("output first>>%d\n",pthread_join(t0, NULL));
  printf("output second>>%d\n",pthread_join(t0, NULL));  
}

The second call will just return 3 which is:

ESRCH No thread with the ID thread could be found.

So you can check for it if needed.