2011-12-16 29 views
1
class c 
{ 
public: 
    int id; 
    boost::thread_group thd; 
    c(int id) : id(id) {} 
    void operator()() 
    { 
     thd.create_thread(c(1)); 
     cout << id << endl; 
    } 


}; 

我創建了類c。每個類對象創建線程以處理工作。錯誤C2248:然而,當我編譯這個C++ Boost,使用類中的thread_group

我得到這個奇怪的消息「提振:: thread_group :: thread_group」:不能訪問類「的boost :: thread_group」

除了宣佈私有成員,只是假設是沒有遞歸調用問題。

回答

3

問題是您的代碼設置方式是傳遞對象的副本以創建新線程。

由於boost :: thread_group的複製構造函數是私有的,因此您無法複製類c的對象。您不能複製類c的對象,因爲默認的複製構造函數試圖複製所有成員,並且它不能複製boost :: thread_group。因此編譯器錯誤。

經典的解決方案是編寫自己的拷貝構造函數,它不會嘗試複製boost :: thread_group(如果實際上每次調用都需要一個唯一的thread_group)或將boost :: thread_group存儲在指針中某種可以複製的類型(可以共享該組,並且可能是您想要的)。

注:

它通常是簡單的不寫自己的運營商(),只是沿着升壓::功能票代替。這將與

#include <boost/thread.hpp> 
#include <iostream> 
using namespace std; 
class c 
{ 
public: 
    boost::thread_group thd; 

    void myFunc(int id) 
    { 
     boost::function<void(void)> fun = boost::bind(&c::myFunc,this,1); 
     thd.create_thread(fun); 
     cout << id << endl; 
    } 


}; 

注意,無論是在C類共享,不管是通過函數調用值傳遞不共享來完成。

+0

但我必須創建具有成員變量和函數的類對象。所以我不能把線程作爲一個單一的功能。無論如何,像我上面所做的那樣創建類對象? – Jaebum 2011-12-16 06:55:40

相關問題