Вопрос

I am trying (using pthread_create) to pass a value to the function:

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,...". 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:

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

and

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

both of which produce the same compiler errors.

Это было полезно?

Решение 2

The error message is pretty clear. You need a function of type void * (void *), and you have a function of type 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".)

Другие советы

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* philosopher(void*);

and inside the philosopher function, you cast the parameter back to an int.

(Don't cast the function - that's undefined.)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top