【发布时间】:2015-02-04 20:37:44
【问题描述】:
在用 C 编写线程代码时,我首先必须创建一些 struct,其中包括所有参数和一个包装函数。这会导致大量代码膨胀并且不易阅读。见:
struct some_function_args {
int arg1;
int arg2;
int arg3;
};
void some_function_wrapper(struct some_function_args* args) {
some_function(args->arg1, args->arg2, args->arg3);
}
int main() {
struct my_args;
my_args.arg1 = 1;
my_args.arg2 = 2;
my_args.arg3 = 3;
pthread_create(..., some_function_wrapper, &my_args);
pthread_join(...);
}
是否有某种宏或库(可能使用varargs)自动为我创建所需的结构和包装函数,像这样?或者这在 C 中根本不可能?
int main() {
MY_THREAD thread = IN_THREAD {
some_function(1, 2, 3);
}
JOIN_THREAD(thread);
}
【问题讨论】:
-
请注意,
some_function_wrapper应采用void*并将其显式转换为struct some_function_args*。否则它将被错误的原型调用,这是未定义的行为。 -
较新的 C 标准 (C99) 具有复合初始化器:
struct my_args = {.arg1 = 1, .arg2 = 2, .arg3 = 3};
标签: c multithreading pthreads c-preprocessor