Why do we use pthread_exit() when we can use return?

pthread_exit() is for threads what exit() is for the main program.

Can you always terminate the main program using return? I guess not. This is why exit() and pthread_exit() exist.

Returning from the main function of the thread performs an implicit call to pthread_exit(). The function is called no matter how you terminate your thread. It is responsible for thread's cleanup.

But if function foo() calls function bar() and bar() decides it must terminate the thread, it's more convenient to call pthread_exit() than to return from bar() and check the return value in foo(). The annoyance with return grows when the number of calls in the chain grows.


The difference between these two is important if you use clean up handlers installed via pthread_cleanup_push

From the pthread_cleanup_push manpages it says:

  1. When a thread is canceled, all of the stacked clean-up handlers are popped and executed in the reverse of the order in which they were pushed onto the stack.
  2. When a thread terminates by calling pthread_exit(3), all clean-up handlers are executed as described in the preceding point. (Clean-up handlers are not called if the thread terminates by performing a return from the thread start function.)

So if you installed clean up handlers they will not be called if you use return but they will be called if you use pthread_exit.

Tags:

Unix

C