Incorrect conversion from 'void * to' void * (*) (void *) C ++?

I try to use pthread_create (), but it always gives me this error the wrong conversion from void* to void* ( * )(void*)

This error is in the third argument. Can someone help me with this error?

 void Print_data(void *ptr) { cout<<"Time of Week = " <<std::dec<<iTOW<<" seconds"<<endl; cout<<"Longitude = "<<lon<<" degree"<<endl; cout<<"Latitude = "<<lat<<" degree"<<endl; cout<<"Height Above Sea = "<<alt_MSL<<" meters"<<endl; } int call_thread() { pthread_create(&thread, NULL, (void *) &Print_data, NULL); return 0; } 
+6
source share
5 answers

The error is that you are converting a function pointer ( void* (*)(void*) ) to an object pointer ( void* ) when pthread_create expects a function pointer for this argument. There is no implicit conversion to undo the tricky conversion you made, hence the error.

The answer is to not do this:

 pthread_create(&thread, NULL, &Print_data, NULL); 

and you will also need to change Print_data to return void* to match the Posix thread interface:

 void *Print_data(void *ptr) { // print stuff return NULL; // or some other return value if appropriate } 

As noted in the comments, there are various other problems using this C library directly from C ++; in particular, for portability, the stream input function must be extern "C" . Personally, I would recommend using the standard C ++ thread library (or the Boost implementation if you are stuck with a language version before 2011).

+16
source

You are trying to convert a function pointer to void* here: (void *) &Print_data

According to pthread_create you need to pass a function that takes void* and returns void*

So your function signature should be

 void* Print_data(void *ptr) 

And your call should be

 pthread_create(&thread, NULL, &Print_data, NULL); 
+4
source

You must return void*

 void* Print_data(void *ptr) { 

to meet the needs.

The signature of the function to be transferred,

 void* function(void*); 

then call pthread_create using

  pthread_create(&thread, NULL, &Print_data, NULL); 
+2
source

pthread_create takes a third argument as

 int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg); 

This, void *(*start_routine)(void*) is a pointer to a function that takes a void* pointer and returns a void* pointer.

When you do &Print_data and convert the pointer to void * , it means that you are passing a pointer of type void* , and not a pointer of type void *(*start_routine)(void*) [function pointer].

To be true, you need to make your return type as void* and make a call as pthread_create(&thread, NULL, &Print_data, NULL);

+2
source

add #include header file and compile g ++ -lpthread

0
source

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


All Articles