Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pthread: Why people bother using pthread_exit?

Tags:

pthreads

As far as I understand, pthread_exit() exactly equals to return when you need terminate a thread with a return value. When people can use the consistent way, i.e. return, to do the job why Pthread define such a duplicated interface?

like image 803
Mengfei Murphy Avatar asked Jan 05 '12 22:01

Mengfei Murphy


People also ask

Is pthread_exit necessary?

You are not required to call pthread_exit . The thread function can simply return when it's finished. From the man page: An implicit call to pthread_exit() is made when a thread other than the thread in which main() was first invoked returns from the start routine that was used to create it.

What is the use of pthread_exit?

The pthread_exit() function terminates the calling thread, making its exit status available to any waiting threads. Normally, a thread terminates by returning from the start routine that was specified in the pthread_create() call which started it.

What happens when you call pthread_exit () in the main thread?

When pthread_exit is used, the main thread will stop executing and will remain in zombie(defunct) status until all other threads exit. If you are using pthread_exit in main thread, cannot get return status of other threads and cannot do clean-up for other threads (could be done using pthread_join(3)).

Is pthread_join necessary?

Yes if thread is attachable then pthread_join is must otherwise it creates a Zombie thread. Agree with answers above, just sharing a note from man page of pthread_join. After a successful call to pthread_join(), the caller is guaranteed that the target thread has terminated.


1 Answers

Two reasons that come to my mind: pthread_exit

  1. Allows you to exit a thread from any depth in the call stack.

  2. Must be called on the main thread if the TLS keys for the main thread are to have their free functions called. And here as well: "Any cancellation cleanup handlers that have been pushed and not yet popped are popped in the reverse order that they were pushed and then executed. After all cancellation cleanup handlers have been executed, if the thread has any thread-specific data, appropriate destructor functions will be called in an unspecified order... An implicit call to pthread_exit() is made when a thread other than the thread in which main() was first invoked returns from the start routine that was used to create it. The function's return value serves as the thread's exit status."

like image 65
Dark Falcon Avatar answered Oct 02 '22 18:10

Dark Falcon