Sreeraj Chundayil
Sreeraj Chundayil

Reputation: 5859

Why pthread_exit acts like pthread_join?

Code:

void *PrintHello(void *threadid)
{
   cout<<"Hello"<<endl;
   sleep(3);
   cout<<"Still PrintHello is alive"<<endl;
}
int main (int argc, char *argv[])
{
   pthread_t threads[NUM_THREADS];
   cout<<"Calling thread:"<<t<<endl;
   pthread_create(&threads[0], NULL, PrintHello, NULL);
   //pthread_join(threads[0],NULL);
   cout<<"Main exits"<<endl;
   pthread_exit(NULL);
}

Why pthread_exit(NULL) here acts like pthread_join()? i.e Why exiting main not destroying the printHello thread and allowing it to continue?

Upvotes: 0

Views: 600

Answers (2)

Mark Smith
Mark Smith

Reputation: 909

There's quite a good resource here but to quote the part which explains your problem:

Discussion on calling pthread_exit() from main():

  • There is a definite problem if main() finishes before the threads it spawned if you don't call pthread_exit() explicitly. All of the threads it created will terminate because main() is done and no longer exists to support the threads.

  • By having main() explicitly call pthread_exit() as the last thing it does, main() will block and be kept alive to support the threads it created until they are done.

Upvotes: 2

P.P
P.P

Reputation: 121397

pthread_exit() terminates only the calling thread. So when you call it from main(), it terminates the main thread while allowing the process to continue. This is as expected.

If you call exit() (or an implicit exit from by returning) instead, it'll terminate the whole process and you will see printHello terminated as well.

Upvotes: 2

Related Questions