2016-05-08 3 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::refまたはstd::refいずれかを使用します。

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

これはまだ値によってコピーされた基準ラッパーを作成しますが、内部で実際の参照を追跡します。

+0

私はこれを早く知っていました。確かに一時的なクラス変数の束を持っているより整頓されたように見えます。 – Ali250

+0

私はまたこれで初めてトラップされました。それが私が知っている理由です;) – axalis

関連する問題