2014-03-27 30 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看到我的新編輯,我想我發現了另一個問題。 –