繁体   English   中英

pthread_create问题

[英]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 ++方法(甚至是静态方法)作为例程传递给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

解决此问题的典型方法是通过void指针(此数据指针在其接口中)将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);
    }   
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM