【问题标题】:Why the second argument to pthread_join() is a **, a pointer to a pointer?为什么 pthread_join() 的第二个参数是一个**,一个指向指针的指针?
【发布时间】:2018-04-23 15:27:20
【问题描述】:

我是使用pthread 的新手,对指针的指针也不熟悉。有人可以解释为什么pthread_join() 的第二个参数是void **。为什么会这样设计。

int pthread_join(pthread_t thread, void **value_ptr);

【问题讨论】:

  • 因为pthread_exit(void* retval);pthread_join()应该能通信失败。

标签: c pointers pthreads pass-by-value pointer-to-pointer


【解决方案1】:

要通过函数的参数返回值,您需要传入变量的地址以接收新值。

由于pthread_join() 被设计为接收传递给pthread_exit() 的指针值,这是一个void*pthread_join() 期望void* 的地址实际上是void** 类型。

例子:

#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;
}

上面的程序预计会打印:

tf(): a[0] = 42
main(): a[1] = 43

【讨论】:

    最近更新 更多