在C編寫線程代碼時,我首先必須創建一些包含所有參數和包裝函數的struct
。這導致大量的代碼膨脹並且不容易閱讀。請參閱:在C中使用pthreads時如何避免代碼膨脹?
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 *'。否則,它會被調用錯誤的原型,這是未定義的行爲。 – Quentin
較新的C標準(C99)有複合初始值設定項:'struct my_args = {.arg1 = 1,.arg2 = 2,.arg3 = 3};' – EOF