如何/为什么要转换为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*)'
我想创建一个运行(仅)函数“producer”的pthread,该函数也包含在与main相同的文件中。为什么这不起作用?
答案 0 :(得分: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));