简体   繁体   中英

What if thread exits before calling pthread_join

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?

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

The join operation will immediately finish and return.

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 (eg exit flags) and check for returned errors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM