Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 478
InQusitive Avatar asked Mar 28 '15 07:03

InQusitive


People also ask

What happens if pthread_join is not called?

If you want to be sure that your thread have actually finished, you want to call pthread_join . If you don't, then terminating your program will terminate all the unfinished thread abruptly.

Does pthread_join terminate a thread?

The pthread_join() function waits for a thread to terminate, detaches the thread, then returns the threads exit status. If the status parameter is NULL, the threads exit status is not returned.

What is the need of having pthread_join () function?

The pthread_join() function provides a simple mechanism allowing an application to wait for a thread to terminate. After the thread terminates, the application may then choose to clean up resources that were used by the thread.

What does pthread_join return?

Return Values pthread_join() returns zero when it completes successfully.


1 Answers

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

The join operation will immediately finish and return.

like image 155
orlp Avatar answered Sep 24 '22 19:09

orlp