gpt4 book ai didi

c++ - pthread_create 问题

转载 作者:太空宇宙 更新时间:2023-11-04 14:12:02 24 4
gpt4 key购买 nike

我有这个代码:

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*)'

最佳答案

解决您的问题的典型方法是通过 void 指针(此数据指针在其接口(interface)中)将 C++ 对象传递给 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 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13751117/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com