错误:从'int(*)(void *)'到'void *(*)(void *)'的转换无效

时间:2016-03-16 15:22:42

标签: c++ pthreads type-conversion

我正在尝试生成pthread并发送一个整数作为参数但是在将参数转换为void时出现以下错误。我试图删除(void *)并隐式转换,但我仍然遇到同样的错误

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;


}

1 个答案:

答案 0 :(得分:1)

定义为int (*)(void*)的函数与定义为void* (*)(void*)的函数不兼容。您需要将probSAT定义为:

void *probSAT(void *);

如果要从此函数有效地返回int,可以返回全局变量的地址,或者(更好的选项)为int分配空间并返回指向该值的指针(并确保在加入主题时取消分配它。)

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);
    }
}