如果我要为以下函数创建一个 pthread。
假设一切都已正确申报。
pthread_create(&threadId, &attr, (void * (*)(void*))function, //what should be the arguments for here??);
int a = 0;
int b = 1;
//c and d are global variables.
void function(int a, int b){
c = a;
d = b;
}
这不起作用。function() 必须只接受一个参数。这就是为什么你必须这样做:
(无效*()(无效))
你告诉你的编译器“不,说真的,这个函数只接受一个参数”,当然它没有。
相反,您需要做的是传递一个参数(比如指向结构的指针),它可以为您提供所需的信息。
编辑:参见此处的示例:pthread 中函数的参数数量
pthread 线程函数始终采用一个void *参数并返回一个void *值。如果要传递两个参数,则必须将它们包装在struct- 例如:
struct thread_args {
int a;
int b;
};
void *function(void *);
struct thread_args *args = malloc(sizeof *args);
if (args != NULL)
{
args->a = 0;
args->b = 1;
pthread_create(&threadId, &attr, &function, args);
}
对于线程函数本身:
void *function(void *argp)
{
struct thread_args *args = argp;
int c = args->a;
int d = args->b;
free(args);
/* ... */
您不需要使用malloc()and free(),但您必须以某种方式确保原始线程不会取消分配或重新使用线程参数struct,直到被调用线程完成它。