2016-02-29 81 views
0

我想啓動執行一些計算的函數的多個實例。該函數採用一個類對象,因爲該類包含shared_mutex我通過引用傳遞它,所以所有線程都通過相同的對象訪問類。
如果我嘗試通過升壓::線程啓動功能(甚至只是一個)我得到的編譯錯誤:如果我直接通過主調用函數傳遞具有互斥體的類對象以通過引用提升::線程

/usr/include/boost/thread/pthread/shared_mutex.hpp:173:9: error: 
‘boost::shared_mutex::shared_mutex(boost::shared_mutex&)’ is private 
    BOOST_THREAD_NO_COPYABLE(shared_mutex) 
    ^
/cl_shared.h:12:7: error: within this context 
class cl_shared { 
    ^

它工作正常。如何多次運行該功能?多線程讀取/寫入該類時,線程安全的互斥體就在那裏。分解它看起來像:

class cl_shared { 
public: 
    //constructor 
    cl_shared() { }; 

    //functions here using the mtx 
    void hello() { 
     cout<<"hello"<<endl; 
    }; 

    boost::shared_mutex mtx; 
    int aint; 
}; 

cl_shared shared; 

int main(int argc, char **argv) { 
// XMA::mov_avg(shared, arg1); //does work 

// boost::thread worker1(XMA::mov_avg, shared, arg1); //error: mutex is private 
// boost::thread worker2(XMA::mov_avg, shared, arg1); //like to start it simultaneously; 
//boost::thread worker1v2(XMA::mov_avg, boost::ref(shared), 0, avg_typ, pos_vel, w_leng, parse); //does compile, but is it ok? 
} 

功能看起來像:

//the function head: 
void mov_avg(cl_shared &shared, int arg1){ 
//do sth. 
} 
+1

http://www.boost.org/doc/html/thread/thread_management.html#thread.thread_management.tutorial.launching – llonesmiz

+0

順便說一句,它說'互斥'的複製構造函數是私人的。 – llonesmiz

+0

http://stackoverflow.com/questions/22354972/boost-thread-use-of-deleted-function-error – llonesmiz

回答

0

由於互斥是不可複製的,其保持它作爲一個非靜態成員的任何對象也是不可複製。 你需要傳遞你的類的實例作爲參考指針。要通過引用來傳遞它,請使用boost::ref(或更好的,std::ref),並確保您的線程函數也通過引用接受它的參數。