pthread_create issue

pthread_create issue

本文关键字:issue create pthread      更新时间:2023-10-16

我有这个代码:

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的论据传递.