[英]pthread_create does not work due to void pointer and integer conversion error
How/why do you convert to/from a void pointer or int? 您如何/为什么要转换为空指针或int?
The following code wrongly generates compiler errors: 以下代码错误地生成了编译器错误:
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--;
}
The following errors appear (all on the pthread_create line): 出现以下错误(全部在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*)'
I want to create a pthread that runs (only) the function "producer" also contained in the same file as main. 我想创建一个运行(仅)函数“生产者”的pthread,该函数也包含在与main相同的文件中。 Why doesn't this work? 为什么不起作用?
Declare producer
the right way: 以正确的方式声明producer
:
void * producer(void * p)
{
intptr_t n = (intptr_t)(p);
// ... use "n"
}
Then: 然后:
int n = 42;
int res = pthread_create(&tid, &attr, producer, (void*)(n));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.