提升线程不填充通过引用传递的本地对象
Posted
技术标签:
【中文标题】提升线程不填充通过引用传递的本地对象【英文标题】:boost thread not populating local objects passed by reference 【发布时间】:2016-05-08 21:23:59 【问题描述】:我的代码设置如下:
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
这似乎工作得很好。为什么?
【问题讨论】:
【参考方案1】:线程参数确实是按值复制的。如果确实需要通过引用传递参数,请使用boost::ref
或std::ref
:
boost::thread thread(&Foo::workToDoInThread, this, boost::ref(to_fill));
这将创建一个引用包装器,它仍然按值复制,但在内部跟踪实际引用。
【讨论】:
希望我早点知道这一点。当然看起来比拥有一堆临时类变量更整洁。 我也是第一次被这个困住。这就是我知道的原因;)以上是关于提升线程不填充通过引用传递的本地对象的主要内容,如果未能解决你的问题,请参考以下文章