Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: invalid conversion from ‘void*’ to ‘void* (*)(void*)’ - 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*)’

Line number 33 is this:

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

Declaration of functionA is this:

void functionA (void*);


Its definition is:

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);
    }
}
like image 596
Aquarius_Girl Avatar asked Aug 01 '12 11:08

Aquarius_Girl


3 Answers

If you look at the manual page you will see that the function argument is

void *(*start_routine) (void *)

That is, a pointer to a function which takes one void * argument and returns void *.

To get rid of your errors, change your function to return void *, and pass it without type-casting it. The return from the thread function can be a simple return NULL if you don't care about the value.

like image 83
Some programmer dude Avatar answered Nov 18 '22 09:11

Some programmer dude


(void *) &functionA will cast your function pointer functionA which is of type void (*)(void*) to a simple void*. The later can't be converted to the first again, so the compiler reports an error. This is one of the reasons why you shouldn't use C-style casts.

Use pthread_create (&A, NULL, functionA, NULL); instead.

Also, the return type of a thread function should be void*, not void. So change void functionA(void*) to void* functionA(void*).

like image 4
Zeta Avatar answered Nov 18 '22 09:11

Zeta


Use

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

instead of casting.

Also the function you use to pass to pthread_create should return a void* so to avoid any problems later, consider changing the function signature to accomodate this.

like image 4
mathematician1975 Avatar answered Nov 18 '22 08:11

mathematician1975