问题描述
我正在尝试生成 pthread 并发送一个整数作为参数,但是在将参数转换为 void 时出现以下错误.我试图删除 (void*) 并使转换隐式,但我仍然遇到相同的错误
I amtrying to spawn pthreads and send an integer as the argument but I am getting the following error when casting the argument to void. I tried to remove (void*) and make the conversion implicit but I still got the same error
error: invalid conversion from ‘int (*)(void*)’ to ‘void* (*)(void*)’ [-fpermissive]
rc=pthread_create(&threads[i],NULL,probSAT, (void *)&threads_args[i]);
void Solver::p(char** argc)
{
argvp=argc;
pthread_t threads[NTHREADS];
int threads_args[NTHREADS];
int i=0;
int rc;
for(i=0;i<5;i++)
if(order_heap.empty())
v[i]=i+1;
else
v[i]=(order_heap.removeMin())+1;
for (i=0;i<32;i++)
{
threads_args[i]=i;
rc=pthread_create(&threads[i],NULL,probSAT, (void *)&threads_args[i]);
}
pthread_exit(NULL);
return;
}
推荐答案
定义为 int (*)(void*)
的函数与定义为 void* (*)(void*)
.您需要将 probSAT
定义为:
A function defined as int (*)(void*)
is not compatible with one defined as void* (*)(void*)
. You need to define probSAT
as:
void *probSAT(void *);
如果你想从这个函数中有效地返回一个 int
,你可以返回一个全局变量的地址或者(更好的选择)为 int
分配空间并返回一个指向它的指针(并确保在加入线程时释放它).
If you want to effectively return an int
from this function, you can either return the address of a global variable or (the better option) allocate space for an int
and return a pointer to that (and ensure you deallocate it when you join the thread).
void *probSAT(void *param) {
int *rval = malloc(sizeof(int));
if (rval == NULL) {
perror("malloc failed");
exit(1);
}
....
*rval = {some value};
return rval;
}
void get_thread_rval(pthread_t thread_id)
{
void *rval;
int *rval_int;
if (pthread_join(thread_id, &rval) != 0) {
perror("pthread_join failed");
} else {
rval_int = rval;
printf("thread returned %d\n", *rval_int);
free(rval_int);
}
}
这篇关于错误:从‘int (*)(void*)’到‘void* (*)(void*)’的无效转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!