所以基本上我正在解决著名的“哲学家用餐”问题,5 个哲学家正在使用克隆生成。关键是我希望每个哲学家都有一个 id(从 0 到 4)。我计划使用 clone 传递参数来做到这一点。这是代码(我省略了一些子函数)
void philoshopher(void* arg)
{
int i = &arg;
while (TRUE)
{
printf("Philosopher %d is thinking", i);
take_forks(i);
printf("Philosopher %d is eating", i);
sleep(2);
put_forks(i);
}
}
int main(int argc, char **argv)
{
int i;
int a[N] = {0,1,2,3,4};
void* arg;
/*
struct clone_args args[N];
void* arg = (void*)args;
*/
if (sem_init(&mutex, 1, 1) < 0)
{
perror(NULL);
return 1;
}
for (i=0;i<N;i++)
{ if (sem_init(&p[i], 1, 1) < 0)
{
perror(NULL);
return 1;
}
}
int (*philosopher[N])() ;
void * stack;
for (i=0; i<N; i++)
{
if ((stack = malloc(STACKSIZE)) == NULL)
{
printf("Memorry allocation error");
return 1;
}
int c = clone(philosopher, stack+STACKSIZE-1, CLONE_VM|SIGCHLD, &a[i]);
if (c<0)
{
perror(NULL);
return 1;
}
}
//Wait for all children to terminate
for (i=0; i<4; i++)
{
wait(NULL);
}
return 0;
}
编译出来后,我得到这个错误:
passing argument 1 of ‘clone’ from incompatible pointer type [enabled by default]
expected ‘int (*)(void *)’ but argument is of type ‘int (**)()’
我也尝试将其转换为空指针,但结果仍然相同:
void* arg;
....
arg = (void*)(a[i]);
int c = clone(...., arg);
任何人都知道如何解决这个问题。感谢您的帮助。
最佳答案
您没有正确声明函数指针。它应该看起来像这样:
int (*philosopher[N])(void*);
基本上,当您声明函数指针时,您必须指定参数类型,因为指向接受不同类型的函数的指针(谢天谢地!)彼此不兼容。
我认为您还需要删除函数调用中 a[i] 之前的 &。这为您提供了一个指向函数指针的指针,显然它只需要一个普通的函数指针。
关于c++ - 混淆克隆传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22688573/