2011-12-14 32 views
0

我成功地使用此頁面底部的代碼將線程附加到類成員:http://www.tuxtips.org/?p=5帶參數的類的pthread成員函數

我不知道如何擴展代碼來封裝一個方法,如void* atom(void *inst)其中*inst是一個包含各種線程參數的結構。具體而言,Netbeans和我都不瞭解example::*f的定義以及它在thread_maker範圍內的有效方式。

回答

1

我認爲使用pthread(採用c回調)之類的東西的更好的解決方案是創建一個包裝函數,以便您可以更容易地操作boost :: functions。這與Using boost::bind() across C code, will it work?類似。

然後,你可以用升壓只是解決您的問題::綁定

class myClass 
{ 
    void atom(myStruct *data); // void return type to keep it similar to other code 
    // You could change it to a void* return type, but then you would need to change the boost::function declarations 
}; 

boost::function<void(void)> function = boost::bind(&myClass::atom,&myClassInstance,&myStructInstance); //bind your function 
boost::function<void(void)>* functionCopy = new boost::function<void(void)> (function); //create a copy on the heap 

pthread_t id; 
pthread_create(&id,NULL,&functionWrapper,functionCopy); 

包裝函數應該是這樣的。

void functionWrapper(void* data) 
{ 

    boost::function<void(void)> *func = (boost::function<void(void)>*) (data); 
    (*func)(); 
    delete(func); 
} 

雖然這種方法可能比手動傳遞數據更多的工作,它更可擴展的,因此很容易綁定任何東西,把它傳遞給啓動線程。最後

編輯

一個注意:myClassInstance和myStructInstance應該在堆上。如果他們在堆棧上,他們可能會在線程啓動之前被刪除。

+0

我不太瞭解函數指針,以瞭解如何通過functionCopy傳遞參數?你能否將顯式傳遞結構的行添加到functionCopy中? – Mikhail 2011-12-15 05:27:00