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/

相关文章:

c++ - 使用 FILE* 的二进制文件 I/O

c++ - 如何从位移中获取 "lost"位?

c++ - 使用 pthread_create 时出现 "Segmentation fault (core dumped)"

c - 解码C中的函数指针

c++ - 从内存位置调用函数指针

c++ - 将枚举类变量保存到 JSON

c++ - 'N' 的无效模板参数,预期的编译时常量表达式

c - pthread_atfork() 被多次调用导致 after fork() 函数被多次调用

c - 如何更改全局数组的元素以供所有线程查看

Javascript 函数作为从 C++ 定义的 QML 属性