C++ P线程。 pthread_create 的参数

标签 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 能够对未知类型的数据做什么?

最佳答案

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

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

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

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

关于C++ P线程。 pthread_create 的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7948710/

相关文章:

python - “损坏的双链表”内存错误 - OpenCV-Python 3.0.0 和 ARM 上的 Numpy

multithreading - 如何正确使用线程专有数据

c - 以编程方式获取线程 CPU 时间的方法,在 C 中,适用于 OpenSolaris 和 Linux

c - 为什么我们可以同时使用函数指针作为 (*func_ptr)() 和 func_ptr() 来调用函数,但数组指针却不能呢?

c++ - 之前和之后的 lower_bound 和 upper_bound

c++ - 需要大尺寸静态数组

python - pybind11:Python 到 C++ 数据类型的转换不起作用

c - pthread mutex unlock 为什么同一个线程?

c++ - Visual Studio 中的模板化函数指针数组

c++ - 指向模板类中成员函数的指针