What if thread exits before calling pthread_join
Asked Answered
M

2

8

I have a small code

void *PrintHello(void *threadid)
{
   cout<<"Hello"<<endl;
   pthread_exit(NULL);
}

int main ()
{
   pthread_t threads_id;
   pthread_create(&threads_id, NULL, PrintHello, NULL);
   int i=0;
   for(;i<100;i++){cout<<"Hi"<<endl;}   
   pthread_join(threads_id,NULL);
   return 0;
}

I am joining the thread sometime after creation. What will happen if the main tries to join a thread which already exited?

Mcclimans answered 28/3, 2015 at 7:22 Comment(2)
The pthread_join() function waits for the thread specified by thread to terminate. If that thread has already terminated, then pthread_join() returns immediately. The thread specified by thread must be joinable.Karakul
Clearly explain in the manual page: If that thread has already terminated, then pthread_join() returns immediately.Danforth
P
11

What will happen if the main tries to join a thread which already exited?

The join operation will immediately finish and return.

Pinhole answered 28/3, 2015 at 7:36 Comment(0)
R
5

Technically there are multiple possible behaviours.

If you join a thread shortly after it dies, the handle may still be valid and pthread_join shall return immediately.

If the thread fully ended before call to pthread_join, the thread_t handle no longer valid and it should return failure with ESRCH.

In very very very extreme case if you join a thread that has been dead long time ago, such handle could be reused and you are joining a different thread.

TL;DR: Do proper synchonizations (e.g. exit flags) and check for returned errors.

Religionism answered 28/3, 2015 at 7:54 Comment(1)
If the thread is joinable, the ID will not (and can't) be reused until somebody joins it. So in the contrary, not joining a joinable thread is bad, because the resources that are reserved for the thread will never be freed.Danforth

© 2022 - 2024 — McMap. All rights reserved.