Reputation: 415
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);
}
Upvotes: 7
Views: 7421
Reputation: 1132
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
.
Upvotes: 3
Reputation: 72425
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.
Upvotes: 16