简体   繁体   中英

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() ? ie Why exiting main not destroying the printHello thread and allowing it to continue?

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.

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.

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