2011-10-19 119 views
1

我想在下面的代碼中創建一個線程,但指向pthread_create方法調用的函數參數的指針只是不讓我編譯我的代碼。pthread_create參數函數指針

請讓我知道我做錯了,我怎麼能解決這個問題在下面的代碼:

#include "RobotNodes.cpp" 

int main(int argc, char** argv){ 

int i, numRobotsToInit = 7; 

//declare run function pointer 
void (*run)(); 

//create array of robot nodes 
RobotNodes* robots[numRobotsToInit]; 

//init robot nodes 
for(i = 0; i<numRobotsToInit; i++){ 
    robots[i] = new RobotNodes(i, 0.2, 0.2); 
} 


for(i = 0; i<numRobotsToInit; i++){ 
     run = &robots[i]->run; 
     pthread_t thread; 
    pthread_create(&thread, NULL, (void*(*)(void*))run, NULL);  
} 
} 

的錯誤,我得到的是這樣的: error: lvalue required as unary ‘&’ operand

編輯:運行( )是類RobotNodes.cpp中的一個方法,該類包含在此類的頂部。

+0

您確定您沒有將免費功能與會員功能混淆嗎? –

回答

4

似乎有在班裏RobotNodes一個非靜態成員函數,你似乎認爲成員函數的類型是void (*)()。如果是這樣,那麼你錯了。

類型非靜態成員的functon和free函數不一樣的,即使他們有完全相同的簽名!

所以我建議你定義一個名爲start靜電功能,如:

class RobotNodes 
{ 
    public: 
     void run(); //define it as you like 

     static void* start(void *pdata) 
     { 
      RobotNodes *robot = static_cast<RobotNodes*>(pdata); 
      robot->run(); //forward it 
      return 0; //or return as the documentation says 
     } 
}; 

然後用start爲:我創建的pthread_t載體外

std::vector<pthread_t> threads(numRobotsToInit); 
for(i = 0; i<numRobotsToInit; i++) 
{ 
    pthread_create(&threads[i], NULL, RobotNodes::start, &robots[i]);  
} 

此外,通知循環;這是因爲每個線程必須不同,如果它們是不同的線程,而且每個線程實例必須繼續存在,即使在循環停止後。

0

運行定義在哪裏?

使用pthread_create(&thread, ...)是壞的,因爲thread是for循環的局部變量,將在for的結尾超出範圍。

嘗試,而不是:

for(i = 0; i<numRobotsToInit; i++){ 
    run = &robots[i]->run; 
    pthread_t* thread = new pthread_t; //you will get a memory leak unless you store these to delete later 
    pthread_create(thread, NULL, run, NULL);  
} 

如果我理解正確的運行功能是RobotNodes一員,在這種情況下,你需要做一個調度程序來調用這個函數,因爲你無法通過成員函數pthread_create

創建一個名爲dispatch的靜態函數,或者將其傳遞給您想要調用該函數的類實例的指針。

+0

抱歉忘記包含run()來自本課程包含的另一個類(RobotNodes)。 當我使用您的更改運行代碼時出現以下錯誤: 錯誤:無法將'void(RobotNodes :: *)()'轉換爲'void(*)()' 錯誤:無效從'void (*)()'to'void *(*)(void *)' error:初始化參數3'int pthread_create(pthread_t *,const pthread_attr_t *,void *(*)(void *),void *)' – freakii

0

問題是您正試圖指定一個指向成員函數的指針,而不是標準函數。

相反,通過機器人作爲參數傳遞給它告訴機器人運行功能:

extern "C" void* run_robot(void* robot) __attribute__((noreturn)); 
void* run_robot(void* robot) { 
    RobotNodes* node(static_cast<RobotNodes*>(robot)); 
    node->run(); 
    pthread_exit(0); 
} 
... 
pthread_create(&thread, NULL, run_robot, &robots[i]);