pthread_create issue
pthread_create issue
我有这个代码:
void* ConfigurationHandler::sendThreadFunction(void* callbackData)
{
const EventData* eventData = (const EventData*)(callbackData);
//Do Something
return NULL;
}
void ConfigurationHandler::sendCancel()
{
EventData* eventData = new EventData();
eventData ->Name = "BLABLA"
pthread_t threadId = 0;
int ret = pthread_create(&threadId,
NULL,
ConfigurationHandler::sendThreadFunction,
(void*) eventData ); // args passed to thread function
if (ret)
{
log("Failed to launch thread!n");
}
else
{
ret = pthread_detach(threadId);
}
}
我收到编译器错误:
error: argument of type 'void* (ConfigurationHandler::)(void*)' does not match 'void* (*)(void*)'
解决问题的典型方法是C++通过 void 指针(此接口中的数据指针)将对象传递给 pthread_create()。传递的线程函数将是全局的(可能是静态函数),它知道 void 指针实际上是一个C++对象。
就像这个例子一样:
void ConfigurationHandler::sendThreadFunction(EventData& eventData)
{
//Do Something
}
// added code to communicate with C interface
struct EvendDataAndObject {
EventData eventData;
ConfigurationHandler* handler;
};
void* sendThreadFunctionWrapper(void* callbackData)
{
EvendDataAndObject* realData = (EvendDataAndObject*)(callbackData);
//Do Something
realData->handler->sendThreadFunction(realData->eventData);
delete realData;
return NULL;
}
void ConfigurationHandler::sendCancel()
{
EvendDataAndObject* data = new EvendDataAndObject();
data->eventData.Name = "BLABLA";
data->handler = this; // !!!
pthread_t threadId = 0;
int ret = pthread_create(&threadId,
NULL,
sendThreadFunctionWrapper,
data );
if (ret)
{
log("Failed to launch thread!n");
}
else
{
ret = pthread_detach(threadId);
}
}
您无法安全地将 C++ 方法(即使是静态方法)作为例程传递给pthread_create
。
假设你不传递一个对象 - 即,ConfigurationHandler::sendThreadFunction
被声明为静态方法:
// the following fn has 'C' linkage:
extern "C" {
void *ConfigurationHandler__fn (void *arg)
{
return ConfigurationHandler::sendThreadFunction(arg); // invoke C++ method.
}
}
ConfigurationHandler__fn
将作为pthread_create
的论据传递.
相关文章:
- Seg Fault Issue C++ (file IO / getline)
- Using C++ CryptAPI:CNG Create CSR
- 错误:(-210:不支持的格式或格式组合)功能'create'中的硬件视频解码器不支持视频源
- Issue with WriteProcessMemory
- std::partition segfault issue
- VSCode C/C++ Intellisense issue: Undefined identifiers (Linu
- OpenGL glBufferSubData Offset issue
- boost::property_tree XML issue
- Firebase C++VS2018 SDL2-在Firebase::app::create(..)上执行异常处理
- qt QWidget::closeEvent link issue
- QT 和 JIRA Rest API: /rest/api/2/issue/createmeta 意外返回韩语的 iss
- QThread::create 似乎没有将参数传递给函数
- Crypto++ GetModulus() issue
- 为什么"non-standard syntax; use '&' to create a pointer to member"在 CTOR 中使用线程?
- QThread::create running on UI Thread
- 空指针(为缺少的输出数组调用的 create() 在 create,文件 /home/m/OpenCV/modules/
- 使用宏替换工厂模式样式 API 中的"create()"函数
- Vector.push_back Issue
- C++嵌套类从嵌套类继承,请键入 issue
- 错误:'create'不是 'cv::Tracker' 的成员