令人困惑的克隆遗传论点

Confusing clone passing down argument

本文关键字:      更新时间:2023-10-16

所以基本上我正在解决着名的"哲学家用餐"问题,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指针,但仍然是相同的结果:

void* arg;
....
arg = (void*)(a[i]);
int c = clone(...., arg);

有人知道如何解决这个问题吗?谢谢你的帮助。

您没有正确声明函数指针。它应该看起来像这样:

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

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

我认为你还需要删除&在函数调用中的a[i]之前。这是给你一个指向函数指针的指针,显然它只需要一个普通的函数指针

相关文章:
  • 没有找到相关文章