c++ - 混淆克隆传递参数

标签 c++ casting arguments clone type-conversion

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

相关文章:

c++ - 这个使用 using 的可变参数模板如何工作?

c++ - 带 API 的实时频谱分析仪

c++ - 在计时器上关闭 QMessageBox,setText 不显示

c++ - 将此 c-cast 更改为 reinterpret_cast 是否安全?

C : Convert Char To Float Produce 0. 000002?

c - C 中的参数变量

c++ - 专门化非模板类的模板化构造函数

c++ - 将整数重新解释为 float 是否安全?

java - 当参数中已提供字节数组对象时,为什么某些 Java 函数需要字节数组长度?

python - 如何使用另一个列表中的列表值作为 Python 中函数的参数