I am trying to use pthread_create() but it always gives me this error invalid conversion from void*
to void* ( * )(void*)
This error is in the 3rd argument. Could 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;
}
The error is that you're converting the function pointer (void* (*)(void*)
) to an object pointer (void*
), when pthread_create
expects a function pointer for that argument. There's no implicit conversion to undo the dodgy conversion you've done, hence the error.
The answer is to not do that:
pthread_create(&thread, NULL, &Print_data, NULL);
and you'll also need to modify Print_data
to return void*
to match the Posix threads 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 issues with using this C library directly from C++; in particular, for portability, the thread entry function should be extern "C"
. Personally, I'd recommend using the standard C++ thread library (or Boost's implementation, if you're stuck with a pre-2011 version of the language).
You're trying to convert a function pointer into a void*
here: (void *) &Print_data
According to pthread_create
you need to pass in a function that takes a void*
and returns a void*
So your function signature should be
void* Print_data(void *ptr)
And your call should be
pthread_create(&thread, NULL, &Print_data, NULL);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With