0

您如何/为什么转换为/从 void 指针或 int 转换?

以下代码错误地生成编译器错误:

while(num_producers > 0) {
    pthread_t tid; // id of pthread (not used except to call pthread_create)
    pthread_attr_t attr; // pthread attributes (not used except to call pthread_create)
    pthread_attr_init(&attr); // default pthread attributes
    pthread_create(&tid, &attr, producer, num_producers);
    num_producers--;
}

出现以下错误(都在 pthread_create 行):

error: invalid conversion from 'void (*)(int)' to 'void* (*)(void*)'
  error: initializing argument 3 of 'int pthread_create(_opaque_pthread)t**, const pthread_attr_t*, void* (*)(void*), void*)'
  error: invalid conversion from 'int' to 'void*'
  error: initializing argument 4 of 'int pthread_create(_opaque_pthread_t**, const pthread_attr_t*, void* (*)(void*), void*)'

我想创建一个运行(仅)函数“生产者”的 pthread,该函数也包含在与 main 相同的文件中。为什么这不起作用?

4

1 回答 1

1

声明producer正确的方法:

void * producer(void * p)
{
    intptr_t n = (intptr_t)(p);

    // ... use "n"

}

然后:

int n = 42;

int res = pthread_create(&tid, &attr, producer, (void*)(n));
于 2013-04-17T21:06:40.080 回答