Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

unix

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);
}
like image 926
Steric Avatar asked Apr 03 '16 06:04

Steric


People also ask

What is the importance of pthread_exit () call?

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.

Does pthread_exit return?

RETURN VALUE The pthread_exit() function cannot return to its caller.

Is pthread_exit necessary?

You are not required to call pthread_exit . The thread function can simply return when it's finished.

What is the difference between return and pthread_exit in a function associated to a thread?

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.


2 Answers

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.

like image 80
axiac Avatar answered Nov 04 '22 16:11

axiac


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.

like image 39
en4bz Avatar answered Nov 04 '22 14:11

en4bz