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
}
}
これはうまくいくようです。どうして?
私はこれを早く知っていました。確かに一時的なクラス変数の束を持っているより整頓されたように見えます。 – Ali250
私はまたこれで初めてトラップされました。それが私が知っている理由です;) – axalis