Question

I can't understand why does pthread_join takes as 2nd argument void** for the return value, whereas pthread_exit, which is given the return value, has the return value argument as void*.

Was it helpful?

Solution

pthread_join waits for the thread to end, and the resulting value from pthread_exit is stored into *value_ptr. If you want to ignore the result, you can pass NULL for the value_ptr. This is the common C practice of simulating pass by reference by passing a pointer to a variable. See Passing by reference in C

The pthread_join returns 0 as the function return value on success; then you know that the thread has been joined, and you can access the value from *value_ptr.

void *value = NULL;
if (pthread_join(thread, &value) == 0) {
    // thread has ended, and the exit value is available in
    // the value variable
} 

OTHER TIPS

Essentially, pthread_join() wants to return two peices of information:

  • a success/failure indication
  • whatever the thread returned (which has a type void*)

In C, the typical way a function 'returns' two separate values is to have the function return one of those values normally and to 'return' the ofther value in a location provided by the caller where the caller passes in a pointer to that location. So pthread_join():

  • returns success/failure as the function's value
  • returns the thread's void* result in a caller-provided location that the caller passes a void** to.

Note that in pthread_join()'s case, the caller-provided location is optional. NULL can be passed in id the caller isn't interested in that result. Making the caller-provided location optional is a common, by by no means universal, idiom.

pthread_exit() doesn't need to use a void** as it's argument because that argument isn't a result of the function. So it can simply take the value directly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top