2014-03-27 93 views
1

所以基本上我正在解决着名的“哲学家就餐”问题,5哲学家使用克隆产生出来。关键是我希望每个哲学家都拥有一个id(从0到4)。我打算使用克隆传递参数来做到这一点。下面是代码(我省略某些子功能)混淆克隆传递参数

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); 

任何人都知道如何解决这个问题。谢谢你的帮助。

回答

0

你没有正确地声明你的函数指针。它应该是这样的:

int (*philosopher[N])(void*); 

基本上当你声明函数指针,必须指定参数类型,因为函数指针接受不同类型的彼此不兼容(谢天谢地!)。

我想你还需要在函数调用[i]之前删除&。这给你一个指向函数指针的指针,它只是期望一个普通的函数指针。

+0

我改变了这句话,但它仍然给出了同样的错误。不知道为什么@@ –

+0

@ thomasdang看到我的新编辑,我想我发现了另一个问题。 –