我想使用在pthread_create(),但它总是给我从这个错误中的无效转换void*到void* ( * )(void*)
此错误在第3个参数中.有人可以帮我解决这个错误吗?
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;
}
Run Code Online (Sandbox Code Playgroud)
Mik*_*our 16
错误是当您需要该参数的函数指针时,您正在将函数pointer(void* (*)(void*))转换为对象指针(void*)pthread_create.没有隐式转换来撤消你已经完成的狡猾的转换,因此错误.
答案是不这样做:
pthread_create(&thread, NULL, &Print_data, NULL);
Run Code Online (Sandbox Code Playgroud)
并且你还需要修改Print_data以返回void*匹配Posix线程接口:
void *Print_data(void *ptr) {
// print stuff
return NULL; // or some other return value if appropriate
}
Run Code Online (Sandbox Code Playgroud)
正如评论中所指出的,直接从C++使用这个C库还有其他各种问题.特别是,为了便携性,线程入口函数应该是extern "C".就个人而言,我建议使用标准的C++线程库(或Boost的实现,如果你坚持使用2011年之前的语言版本).
你必须返回void*
void* Print_data(void *ptr) {
Run Code Online (Sandbox Code Playgroud)
以满足需要。
要传递的函数的签名是
void* function(void*);
Run Code Online (Sandbox Code Playgroud)
然后pthread_create使用调用
pthread_create(&thread, NULL, &Print_data, NULL);
Run Code Online (Sandbox Code Playgroud)