2013-02-28 92 views
3

我想以一種方式試驗C++ 11線程,它接受一個類的成員函數作爲線程構造函數的一個參數,如下面第一行代碼片段所示20標記。類定義在第二個代碼片段中給出。當這段代碼被編譯時,我得到了第三段代碼中顯示的一堆錯誤。誰能告訴我我做錯了什麼?謝謝。執行一個類的成員函數

SNIPPET 1:螺紋初始化(main_app.cpp)

#include <thread> 
#include "ServiceRegistrar.hpp" 

#define SERVER_TYPE 100065 
#define SERVER_INST_LOWER 1 
#define SERVER_INST_UPPER 2 
#define TIMEOUT 500000 

int main() 
{ 
    ServiceRegistrar sr1(SERVER_TYPE, TIMEOUT, SERVER_INST_LOWER, SERVER_INST_LOWER); 
     /*LINE 20 is the following*/ 
    std::thread t(&ServiceRegistrar::subscribe2TopologyServer, sr1); 
t.join(); 
    sr1.publishForSRs(); 

} 

SNIPPET 2:類定義

class ServiceRegistrar 
{ 
    public: 
    ServiceRegistrar(int serverType, int serverTimeOut, int serverInstanceLower, int serverInstanceUpper) 
     : mServerType(serverType), 
     mServerTimeOut(serverTimeOut), 
     mServerInstanceLower(serverInstanceLower), 
     mServerInstanceUpper(serverInstanceUpper) 
     { } 

    void subscribe2TopologyServer(); 
    void publishForSRs(); 
    void publishForServices(); 

    private: 
    int mServerType; 
    int mServerTimeOut; 
    int mServerInstanceLower; 
     int mServerInstanceUpper;   
    }; 

SNIPPET 3:編譯輸出

$ g++ -g -c -Wall -std=c++11 main_app.cpp -pthread 
    In file included from /usr/include/c++/4.7/ratio:38:0, 
      from /usr/include/c++/4.7/chrono:38, 
      from /usr/include/c++/4.7/thread:38, 
      from main_app.cpp:8: 
    /usr/include/c++/4.7/type_traits: In instantiation of ‘struct std::_Result_of_impl<false, false, std::_Mem_fn<void (ServiceRegistrar::*)()>, ServiceRegistrar>’: 
    /usr/include/c++/4.7/type_traits:1857:12: required from ‘class std::result_of<std::_Mem_fn<void (ServiceRegistrar::*)()>(ServiceRegistrar)>’ 
    /usr/include/c++/4.7/functional:1563:61: required from ‘struct std::_Bind_simple<std::_Mem_fn<void (ServiceRegistrar::*)()>(ServiceRegistrar)>’ 
/usr/include/c++/4.7/thread:133:9: required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (ServiceRegistrar::*)(); _Args = {ServiceRegistrar&}]’ 
main_app.cpp:20:64: required from here 
/usr/include/c++/4.7/type_traits:1834:9: error: no match for call to  ‘ (std::_Mem_fn<void (ServiceRegistrar::*)()>) (ServiceRegistrar)’ 
+1

ewwww非常不必要的宏。 – Puppy 2013-02-28 19:00:39

回答

4

顯然,這是一個gcc 4.7 bug ...使用

std::thread t(&ServiceRegistrar::subscribe2TopologyServer, &sr1); 

代替。

編輯:實際上,你可能不想將sr1複製到t的線程本地存儲,所以這是更好的。

+0

錯誤與否,你幾乎肯定想要在這裏綁定一個指針或引用。 – 2013-02-28 18:41:17

+0

@MikeSeymour是的,只是補充說明 – 2013-02-28 18:42:32

0

嘗試:

std::thread t(std::bind(&ServiceRegistrar::subscribe2TopologyServer, sr1)); 

希望它能幫助。

+1

這掩蓋了這個問題,因爲'bind'與'thread'沒有共同的bug。但綁定到'sr1'的副本幾乎肯定是錯誤的。 – 2013-02-28 18:47:49

+0

同意,我通常使用指針或shared_ptr – zzk 2013-02-28 19:06:08

相關問題