我想在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/