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

时间:2012-08-01 11:20:52

标签: c++ linux g++ pthreads

anisha@linux-y3pi:~> g++ conditionVarTEST.cpp -Wall

conditionVarTEST.cpp: In function ‘int main()’:
conditionVarTEST.cpp:33:53: error: invalid conversion from ‘void*’ to ‘void* (*)(void*)’
conditionVarTEST.cpp:33:53: error:   initializing argument 3 of ‘int pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*)’
conditionVarTEST.cpp:34:53: error: invalid conversion from ‘void*’ to ‘void* (*)(void*)’
conditionVarTEST.cpp:34:53: error:   initializing argument 3 of ‘int pthread_create(pthread_t*, const pthread_attr_t*, void* (*)(void*), void*)’

第33行是:

pthread_create (&A, NULL, (void *) &functionA, NULL);

functionA的声明是:

void functionA (void*);


其定义是:

void functionA (void* argA)
{
    while (1)
    {
        pthread_mutex_lock (&mutexA);

        if (count < 0)
        {
            pthread_cond_wait (&conditionVariableA, &mutexA);
        }
        else
        {
            // Do something.
            std :: cout << "\nTime to enjoy!";
        }
        pthread_mutex_unlock (&mutexA);
    }
}

4 个答案:

答案 0 :(得分:15)

如果查看manual page,您会看到函数参数是

void *(*start_routine) (void *)

即指向函数的指针,该函数接受一个void *参数并返回void *

要解决您的错误,请更改您的函数以返回void *,并在不进行类型转换的情况下传递它。如果你不关心价值,那么线程函数的返回可以很简单return NULL

答案 1 :(得分:3)

(void *) &functionA会将类型为functionA的函数指针void (*)(void*)强制转换为简单void*。后者无法再次转换为第一个,因此编译器报告错误。这是你不应该使用C风格演员表的原因之一。

改为使用pthread_create (&A, NULL, functionA, NULL);

此外,线程函数的返回类型应为void*,而不是void。因此,将void functionA(void*)更改为void* functionA(void*)

答案 2 :(得分:3)

使用

pthread_create (&A, NULL, functionA, NULL); 

而不是施法。

您用来传递给pthread_create的函数也应该返回void*以避免以后出现任何问题,请考虑更改函数签名以适应这一点。

答案 3 :(得分:3)

当您使用C ++编译器时,您应该使用具有C绑定的函数,因为pthread_create需要C函数:

extern "C" void* functionA (void*);

C ++和C可能在您当前的平台上具有相同的调用约定,但没有保证,这将是其他平台上的情况,或将来也是如此。

相关问题