如何将pthread不仅用于c/c 中的void参数的void函数



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

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

我在Internet中找到的start_routine的所有示例都是void *的类型,具有单个void *参数类型,是否可以在pthread_create中使用多个非空间类型参数调用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 = %dn", s.x, s.y, z);
 }

此打印:

41 + 1 = 42

往返intptr_t的铸造对于确保滥用指针值作为整数不违反C标准。

如果您查看手册页,您将看到函数参数为

void *(*start_routine) (void *).

您不能传递其他类型的函数来启动例程。

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

您可以将pthread指针投放到与整数兼容的某种类型。更好的解决方案是将整个功能放在包装器功能中。请参阅以下链接:

c ,创建一个具有返回类型的函数的pthread?

让我们看看我是否理解了这个问题。您想调用带有签名的函数,例如

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对象并相应地填充。当心此对象寿命....

最新更新