简体   繁体   English

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

[英]Trying to cast integer to void to pass to pthread function by value

I am trying (using pthread_create) to pass a value to the function: 我正在尝试(使用pthread_create)将值传递给函数:

void philosopher(int);

I only need a way to differentiate between each thread. 我只需要一种区分每个线程的方法。 It does not matter which order they run in (clearly, since they are threads), nor even which order they were created in, but they need to contain a least one difference so that I can tell the difference between them. 它们以哪个顺序运行(很明显,因为它们是线程),甚至以它们创建的顺序都无关紧要,但是它们需要包含至少一个差异,以便我可以分辨出它们之间的差异。 The reason for this is that, in the function, each thread needs to refer to itself as "philosopher 1, philosopher 2,...". 原因是,在函数中,每个线程都需要将自己称为“哲学家1,哲学家2,...”。 The number of philosophers is dynamic (the user passes it as an argument when running the program). 哲学家的人数是动态的(用户在运行程序时将其作为参数传递)。

pthread_t threads[philo];

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

I get an error from the above code: "invalid conversion from ' void (*)(int)' to 'void* (*)(void*) ' [-fpermissive]. Clearly, I need to pass i by value (because i changes in the for loop). I am stuck at compile time, however, and have only ever been able to have my pthread programs compile when the last value was NULL. I have also tried: 我从上面的代码中得到一个错误:“从' void (*)(int)' to 'void* (*)(void*) '[-fpermissive]的无效转换。很明显,我需要按值传递i(因为我在for循环中更改),但是我停留在编译时,并且只有在最后一个值为NULL时才可以编译我的pthread程序。

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

and

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

both of which produce the same compiler errors. 两者都会产生相同的编译器错误。

You're having problem with a different parameter than you think - it's the thread function that's the problem. 您遇到了与您想象的参数不同的问题-问题在于线程函数。

It's supposed to take a void * - not an int - and return a void * , so change it to 它应该接受一个void * -不是一个int并返回一个void * ,因此将其更改为

void* philosopher(void*);

and inside the philosopher function, you cast the parameter back to an int . 然后在philosopher函数中,将参数转换回int

(Don't cast the function - that's undefined.) (不强制转换功能-这是未定义的。)

The error message is pretty clear. 错误消息很清楚。 You need a function of type void * (void *) , and you have a function of type void (int) . 您需要一个类型为void * (void *)的函数,并且您需要一个类型为void (int)的函数。 Fix it: 修理它:

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

    // ...

    return nullptr;
}

(As @Deduplicator mentioned, strictly speaking pthread_create requires that the thread function have C linkage, so in C++ you need to declare it as extern "C" .) (如@Deduplicator所述,严格来说pthread_create要求线程函数具有C链接,因此在C ++中,您需要将其声明为extern "C" 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM