c - 如何在 C/C++ 中使用 pthread 而不仅仅是带有 void 参数的 void 函数?

标签 c types casting pthreads

我想在main()中调用多个函数并处理它们的返回值(使用pthread_join),但它们都是int函数带有多个非void参数,pthread_create的定义是:

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

我在互联网上找到的所有start_routine 的例子都是void * 类型和单个void * 参数类型,是否可能在 pthread_create 中调用具有多个非 void 类型参数的 int 函数?

最佳答案

您想将 int 函数包装成所需类型的函数。

所以假设你想返回一个 int 你可以这样做:

(该示例假设为 C99,并为了可读性而省略了相关的错误检查。)

#include <inttypes.h> /* for intptr_t */
#include <stdio.h>
#include <pthread.h>

struct S
{
  int x;
  int y;
};

int sum(int x, int y)
{
  return x + y;
}

void * thread_function(void * pv)
{
  struct S * ps = pv;
  pthread_exit((void *) (intptr_t) sum(ps->x, ps->y));
}


int main(void)
{
  struct S s = {41, 1};
  pthread_t pt;
  pthread_create(&pt, NULL, thread_function, &s);

  void * pv;
  pthread_join(pt, &pv);

  int z = (intptr_t) pv;
  printf("%d + %d = %d\n", s.x, s.y, z);
 }

这打印:

41 + 1 = 42

intptr_t 的转换是必要的,以确保将指针值误用为整数不违反 C 标准。

关于c - 如何在 C/C++ 中使用 pthread 而不仅仅是带有 void 参数的 void 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30234026/

相关文章:

swift - 将 NSImage 类型转换为 Any 并将其向下转换回 NSImage

c - C中带指针的for循环

c - 下面的 Linux 驱动程序 C 代码是否有一个 off by one 错误?

c - 你如何清除 C 中的字符串 vector ?

c - 如何在C代码中获取变量的类型?

python - 如何在Python中将 '+'转换为+

c# - 如何使用反射访问私有(private)基类字段

python - 由列表构造函数转换为 int 的字节

c - 为什么这个转换为 void 指针有效?

c - 为什么 PSTR 类型在不同的 visual studio 项目类型上有不同的行为?