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
If you're going to call pthread_exit a duplicated interface, then you should also call exit()
a duplicated interface, since you could exit the program at an arbitrary point. You probably want to call pthread_exit()
when you have some sort of error condition where you simply cannot continue. Or, alternatively, you've found whatever value you're looking for inside of the thread.
As for it's real existence, according to the documentation:
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.
So if you did a return <some pointer>
from the thread, or simply reached the end, pthread_exit()
would be called anyway. It's the same with exiting from main()
, if you return 0
you're actually calling exit(0)
. The function has to exist, otherwise the kernel would not have a way of determining if the thread exited.
Two reasons that come to my mind: pthread_exit
Allows you to exit a thread from any depth in the call stack.
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."