2013-03-06 86 views
0

我是C++的新手,如果能指出可能存在的問題,將不勝感激。我正在嘗試使用調用函數的boost線程。我編輯了工作代碼來介紹線程。在受保護的方法內提升線程功能

在.H我在.cpp文件中有

class Base: public test 
{ 
public: 
    Base(string Name, string test); 

    virtual ~Base(); 


    Base &operator=(const Base &other); 

    Base(const Base &other); 
protected: 
    virtual void Run(); 
private: 
    void RunBasic(); 
    void workerFunc(); 
} 

void Base::Run() 
{ 
    boost::thread workerThread(workerFunc); 
    RunBasic(); 
    workerThread.join(); 
} 

void Base::workerFunc() 
{ 
    #pretending to do some work 
    #some functionality here 
} 

void Base::RunBasic() 
{ 
#more stuff here 
} 

我得到一個編譯錯誤error: no matching function for call to ‘boost::thread::thread(<unresolved overloaded function type>)’

回答

0

錯誤的原因是一旦你解決,你會得到另一個錯誤,這是把你需要說&Base::workerFunc

成員函數的地址是一個非靜態成員功能不能被稱爲沒有對象,所以你需要傳遞一個對象(或對象指針)到thread構造:

boost::thread workerThread(&Base::workerFunc, this); 

這就告訴thread對象來創建一個新的線程,然後RU所以現在應該工作。

如果函數有參數,這在this參數後,通過他們:

boost::thread workerThread(&Base::workerFunc, this, arg1, arg2); 
+0

非常感謝你們。 – user2137735 2013-03-06 18:02:08

0

因爲workerFunc是一個成員函數,你會必須將其綁定到線程。

boost::thread workerThread(&Base::workerFunc, this); 
+0

不,'的boost :: thread'實現_INVOKE_協議,所以'bind'是多餘的,只是'的boost ::線程workerThread(&Base :: workerFunc,this)' – 2013-03-06 15:48:47

+0

@JonathanWakely我沒有意識到這一點,我編輯了我的答案。 – 2013-03-06 15:50:07