如何在C / C ++中使用pthread而不仅仅是void函数的void函数?

时间:2015-05-14 09:40:55

标签: c types casting pthreads

我想在pthread_join中调用多个函数并处理它们的返回值(使用main()),但它们都是 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 *个参数,是否可以使用多个非void类型参数调用int函数在pthread_create

4 个答案:

答案 0 :(得分:1)

您希望将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标准。

答案 1 :(得分:0)

如果查看manual page,您会看到函数参数是

void *(*start_routine) (void *).

您无法通过其他类型的功能来启动例程。

您可以使用(void *)将参数传递给start_routine。

答案 2 :(得分:0)

您可以将pThread指针强制转换为某种与整数兼容的类型。更好的解决方案是将整个功能放在包装函数中。请参阅以下链接:

C++, create a pthread for a function with a return type?

答案 3 :(得分:0)

让我们看看我是否理解了这个问题。 您想要调用具有

等签名的函数
int myfunct(int a, int b, int c)

然后定义像这样的结构

struct my_funct_param_t
{
    int a ;
    int b ;
    int c ; 
} ;

和一个用作启动例程的包装器

void *myfunct1(void *arg)
{
    my_funct_param_t *arg1 = (my_funct_param_t *)arg ;
    myfunct(arg1->a, arg1->b, arg1->c) ;
 ....
}

启动线程的代码必须创建my_funct_patam_t对象并相应填写。小心这个对象的生命周期......