为什么pthread_join()的第二个参数是**,即指向指针的指针? [英] Why the second argument to pthread_join() is a **, a pointer to a pointer?

查看:481
本文介绍了为什么pthread_join()的第二个参数是**,即指向指针的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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);

推荐答案

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

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

pthread_join() 旨在用于接收指针值传递给 pthread_exit() ,它是void* pthread_join() 期望实际上是void*的地址的类型为void**.

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**.

示例:

#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[0]);

  ++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

这篇关于为什么pthread_join()的第二个参数是**,即指向指针的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆