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?
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.