Why the second argument to pthread_join() is a **, a pointer to a pointer?
Asked Answered
B

2

15

I am new to using pthread and also not that familiar with pointers to pointers. Could somebody perhaps explain why the second argument of pthread_join() is a void **. Why is it designed like this.

int pthread_join(pthread_t thread, void **value_ptr);
Busra answered 10/11, 2017 at 11:48 Comment(1)
Because pthread_exit(void* retval); and pthread_join() should be able to communicate failure.Peddling
F
13

To return a value via a function's argument you need to pass in the address of the variable to receive the new value.

As pthread_join() is designed to receive the pointer value being passed to pthread_exit(), which is a void*, pthread_join() expects the address of a void* which in fact is of type void**.

Example:

#include <stdlib.h> /* for EXIT_xxx macros */
#include <stdio.h> /* for printf() and perror() */
#include <pthread.h> 

void * tf(void * pv)
{
  int * a = pv;
  size_t index = 0;

  printf("tf(): a[%zu] = %d\n", index , a[index]);

  ++index;

  pthread_exit(a + index); /* Return from tf() the address of a's 2nd element. 
                          a + 1 here is equivalent to &a[1]. */
}


int main(void)
{
  int a[2] = {42, 43};
  pthread_t pt;
  int result = pthread_create(&pt, NULL, tf, a); /* Pass to tf() the address of 
                                                    a's 1st element. a decays to 
                                                    something equivalent to &a[0]. */
  if (0 != result)
  {
    perror("pthread_create() failed");
    exit(EXIT_FAILURE);
  }

  {
    int * pi;
    size_t index = 0;

    {
      void * pv;
      result = pthread_join(pt, &pv); /* Pass in the address of a pointer-variable 
                                         pointing to where the value passed to 
                                         pthread_exit() should be written. */
      if (0 != result) 
      {
        perror("pthread_join() failed");
        exit(EXIT_FAILURE);
      }

      pi = pv;
    }

    ++index;

    printf("main(): a[%zu] = %d\n", index, pi[0]);
  }

  return EXIT_SUCCESS;
}

The program above is expected to print:

tf(): a[0] = 42
main(): a[1] = 43
Forwards answered 10/11, 2017 at 16:31 Comment(0)
V
0

Basically pthread_join() links the void *joinPointer and the void *exitPointer via its void **value_ptr;

// void *joinPointer; (the pointer you gave to pthread_join)
// void *exitPointer; (the pointer you gave to pthread_exit)

void pthread_exit(void *retval);

int pthread_join(pthread_t thread, void **value_ptr){
       ...
       *value_ptr = <retval>;    //retval points to what exitPointer pointed to
       ...
}

int main(){
       ...
       void *joinPointer;
       ...
       pthread_join(ithread, &joinPointer)
       ...
}
Venereal answered 26/10, 2023 at 23:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.