2016-05-08 47 views
1

通過本地對象,我有我的代碼的設置是這樣的:提升線程不填充引用

class Foo 
{ 
    void doWork(std::vector<int>& to_fill) 
    { 
    //do some of the filling in another thread 
    boost::thread thread(&Foo::workToDoInThread, this, to_fill); 

    //do some filling in the main calling thread 
    std::vector<int> new_to_fill; 
    new_to_fill.push_back(0);  //other, similar operations 

    //in case the other thread is still working, wait for it to finish 
    thread.join(); 

    //combine the two vectors: 
    to_fill.insert(to_fill.end(), new_to_fill.begin(), new_to_fill.end(); 

    } 

    void workToDoInThread(std::vector<int>& to_fill) 
    { 
    to_fill.push_back(1);  //other, similar operations 
    } 
} 

這裏的問題是,如果它被調用join()後立即檢查to_fill向量是空的。所以基本上我放棄了其他線程填充的所有值。但如果我這樣做:

class Foo 
{ 
    std::vector<int> temp_to_fill; 

    void doWork(std::vector<int>& to_fill) 
    { 
    //do some of the filling in another thread 
    boost::thread thread(&Foo::workToDoInThread, this); 

    //do some filling in the main calling thread 
    std::vector<int> new_to_fill; 
    new_to_fill.push_back(0);  //other, similar operations 

    //in case the other thread is still working, wait for it to finish 
    thread.join(); 

    //combine the two vectors: 
    to_fill.insert(to_fill.end(), new_to_fill.begin(), new_to_fill.end(); 
    to_fill.insert(to_fill.end(), temp_to_fill.begin(), temp_to_fill.end(); 

    //clear the temp vector for the next call 
    temp_to_fill.clear(); 

    } 

    void workToDoInThread() 
    { 
    temp_to_fill.push_back(1);  //other, similar operations 
    } 
} 

這似乎工作得很好。爲什麼?

回答

2

線程參數確實是按值複製的。如果你真的需要通過引用傳遞參數,使用boost::refstd::ref

boost::thread thread(&Foo::workToDoInThread, this, boost::ref(to_fill)); 

這將創建一個參考的包裝,它仍然值複製,但在內部跟蹤實際的參考。

+0

希望我早點知道這一點。當然,看起來更加整齊,然後有一堆臨時類變量。 – Ali250

+0

我也第一次被這個人困住了。這就是我知道的原因;) – axalis