gpt4 book ai didi

c++ - boost 线程不填充通过引用传递的本地对象

转载 作者:行者123 更新时间:2023-11-30 03:41:57 24 4
gpt4 key购买 nike

我的代码设置如下:

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 vector ,则该 vector 为空。所以基本上我丢失了由另一个线程填充的所有值。但是如果我这样做:

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
}
}

这似乎工作得很好。为什么?

最佳答案

线程参数确实是按值复制的。如果您确实需要通过引用传递参数,请使用 boost::refstd::ref:

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

这会创建一个引用包装器,它仍然按值复制,但会在内部跟踪实际引用。

关于c++ - boost 线程不填充通过引用传递的本地对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37104966/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com