In the following program return p
gives the same output as pthread_exit(p)
. Then why to use pthread_exit()
?
void *foo(void *p){
*((int *)p) += 1;
pthread_exit(p);
}
int main()
{
pthread_t t;
int i=9;
int *j;
pthread_create(&t,NULL, foo, &i);
pthread_join(t,(void**)&j);
printf("%d\n",*j);
}
The pthread_exit() function terminates the calling thread and makes the value value_ptr available to any successful join with the terminating thread. 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.
RETURN VALUE The pthread_exit() function cannot return to its caller.
You are not required to call pthread_exit . The thread function can simply return when it's finished.
Also, in main() , return will implicitly call exit() , and thus terminate the program, whereas pthread_exit() will merely terminate the thread, and the program will remain running until all threads have terminated or some thread calls exit() , abort() or another function that terminates the program.
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:
- 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.
- 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With