尝试将整数转换为void以按值传递给pthread函数

时间:2014-05-03 21:16:12

标签: c++ c multithreading pthreads typecasting-operator

我正在尝试(使用pthread_create)将值传递给函数:

void philosopher(int);

我只需要一种方法来区分每个线程。它们运行的​​顺序无关紧要(显然,因为它们是线程),甚至它们的创建顺序也没关系,但它们需要包含至少一个差异,以便我可以区分它们。这样做的原因是,在函数中,每个线程需要将自己称为“哲学家1,哲学家2,..."”。哲学家的数量是动态的(用户在运行程序时将其作为参数传递)。

pthread_t threads[philo];

for (int i = 0; i < philo; i++)
    pthread_create(&threads[i], NULL, &philosopher, reinterpret_cast<void*>(i));

我从上面的代码中收到错误:&#34;来自“void (*)(int)’ to ‘void* (*)(void*)”[-fpermissive]的无效转换。显然,我需要通过值传递i(因为我在for循环中更改)。但是,我在编译时遇到困难,并且只有在最后一个值为NULL时才能编译我的pthread程序。我也尝试过:

pthread_create(&threads[i],  NULL,  &philosopher,  i);

pthread_create(&threads[i],  NULL,  &philosopher,  (void*)i);

两者都会产生相同的编译错误。

2 个答案:

答案 0 :(得分:3)

您遇到的问题与您想象的不同 - 它是解决问题的线程函数。

它应该采用void * - 而不是int - 并返回void *,因此请将其更改为

void* philosopher(void*);

并在philosopher函数内,将参数强制转换为int

(不要施放这个功能 - 这是未定义的。)

答案 1 :(得分:2)

错误信息非常清楚。您需要类型为void * (void *)的函数,并且您具有类型为void (int)的函数。解决它:

extern "C"
void * philosopher(void * data)
{
    uintptr_t n = reinterpret_cast<uintptr_t>(data);

    // ...

    return nullptr;
}

(正如@Deduplicator所提到的,严格来说pthread_create要求线程函数具有C链接,因此在C ++中你需要将它声明为extern "C"。)