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:

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

The declaration of functionA is as follows:

void functionA (void*);


Its definition:

 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); } } 
+6
source share
4 answers

If you look at the man page , you will see that the function argument

 void *(*start_routine) (void *) 

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

To get rid of your mistakes, change your function to return void * , and pass it without entering a type. Returning from a stream function can be a simple return NULL if you don't care about the value.

+13
source

(void *) &functionA will output your pointer to functionA , which is of type void (*)(void*) , on a simple void* . A later version cannot be converted for the first time, so the compiler reports an error. This is one of the reasons why you should not use C-style cast.

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

In addition, the return type of the stream function must be void* , not void . Therefore, change void functionA(void*) to void* functionA(void*) .

+3
source

And since you are using a C ++ compiler, you should use a function with a C binding, since pthread_create expects a C function:

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

C ++ and C may have the same calling conventions on your current platform, but there is no guarantee that this will be the case on other platforms or in the future.

+3
source

Use

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

instead of casting.

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

+2
source

Source: https://habr.com/ru/post/921839/


All Articles