C ++ Pthreads。 pthread_create的参数

时间:2011-10-30 23:39:45

标签: c++ pthreads function-pointers void-pointers

关于函数pthread_create,有几点我不明白。

这是标题

int pthread_create(pthread_t *restrict thread,
                   const pthread_attr_t *restrict attr,
                   void *(*start_routine)(void*), 
                   void *restrict arg);

首先,我不熟悉void *(*start_routine)(void*),的语法。我知道这里要求的参数是返回void *的函数的名称,并以void *为参数。据推测,pthread_create将该函数称为start_routine。所以我认为这个参数将是一个函数指针?如果是这样,那么关键的语法元素是什么呢?

其次,为什么pthread_create期望具有void *作为返回类型的函数? pthread_create能够对未知类型的数据做什么?

2 个答案:

答案 0 :(得分:3)

应按以下顺序阅读void *(*start_routine)(void*)

  • start_routine - 参数的名称。
  • *start_routine - 所以这个参数是一个指针。
  • (*start_routine)(...) - 啊哈,它是指向函数的指针。
  • (*start_routine)(void*) - 我们现在知道函数的参数。
  • void *(*start_routine)(void*) - 最后,这告诉我们函数的返回类型。

void*参数接收传递给arg的任何内容 - 因此,如果您需要将任何“输入”传递给新线程,这是一种方法。

结果void*用作线程的退出状态(作为显式调用pthread_exit()的替代方法)。您可以通过pthread_join()获得此状态。

答案 1 :(得分:1)

  1. void *(*start_routine)(void*)是一个函数指针。关于它的一切都是'关键语法',但特别是语法(*ptrname)(args)

  2. pthreads对启动例程返回的void *没有做任何事情,除非将它返回给你。请参阅pthread_join的手册页,了解它是如何回复给您的。