【问题标题】:Confusing clone passing down argument令人困惑的克隆传递参数
【发布时间】:2014-05-06 11:35:30
【问题描述】:

所以基本上我正在解决著名的“哲学家用餐”问题,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);

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

【问题讨论】:

    标签: c++ casting arguments clone type-conversion


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 我更改了短语,但仍然给出相同的错误。不知道为什么@@
    • @thomasdang 看到我的新编辑,我想我发现了另一个问题。
    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 2022-01-17
    • 2018-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    相关资源
    最近更新 更多