2012-12-06 61 views
1

我有這樣的代碼:在pthread_create問題

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

你不能安全地傳遞一個C++方法 - 即使是一個靜態方法 - 作爲一種常規來'pthread_create'。 –

+0

什麼是更好的方法?我如何才能實現上述功能? – Kam

回答

0

您的問題的典型方法是通過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); 
    } 
} 
0

你不能安全地傳遞一個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傳遞。

+0

爲什麼你不能安全地傳遞一個C++靜態方法或函數? –

+0

@ slavik262:因爲C和C++調用約定可能不同。調用C語言中未聲明爲「C」的C++函數也不安全。 – drizzd