Multithreading 在循环中使用boost::promise和boost::future
我想在编译时启动一个未定义数量的线程,并一起等待它们的结果 我想使用boost::thread和boost::promise,::共享未来。 我有以下代码: 为简单起见,这只返回一个整数值Multithreading 在循环中使用boost::promise和boost::future,multithreading,boost,Multithreading,Boost,我想在编译时启动一个未定义数量的线程,并一起等待它们的结果 我想使用boost::thread和boost::promise,::共享未来。 我有以下代码: 为简单起见,这只返回一个整数值 class Test { public: static void histograms(boost::promise<int>& p) { p.set_value(16); } }; 以下是我如何称呼使用承诺和未来: int main() { // vector with
class Test
{
public:
static void histograms(boost::promise<int>& p)
{
p.set_value(16);
}
};
以下是我如何称呼使用承诺和未来:
int main()
{
// vector with final results
std::vector<int> results;
// vector with all futures from boost threads
std::vector<boost::shared_future<int>> futures;
// loop through all operations
for (int i = 0; i < 7; i++)
{
// setup boost future and promise
boost::promise<int> p;
boost::shared_future<int> f = p.get_future();
// add future to the vector to access it later
futures.push_back(f);
boost::thread t{ histograms, std::ref(p) };
}
for (int i = 0; i < futures.size(); i++)
{
在这一行中,我得到了一个违反承诺的例外:
results.push_back(futures[i].get());
}
for (int i : results)
{
std::cout << i << std::endl;
}
system("pause");
return 0;
}
我希望它在启动7个线程时打印出7行,在本例中应该得到7个结果。但这是它第一次到达期货线[i]。get我立即得到一个违反承诺的例外情况。这是一种未定义的行为 您可以在范围内创建promise实例作为局部变量。当作用域消失时,p被破坏,线程函数-直方图中有悬空引用 解决方案? 您可以将承诺存储在智能指针共享\u ptr中以延长其生命周期
class Test
{
public:
static void histograms(boost::shared_ptr< boost::promise<int> > p)
{
p->set_value(16);
}
};
及
在[1]中,p通过值传递给增量参考计数器。因此,即使for循环范围消失,线程函数直方图工作的承诺仍然存在
for (int i = 0; i < 7; i++)
{
boost::shared_ptr< boost::promise<int> > p = boost::make_shared< boost::promise<int> >();
boost::shared_future<int> f = p->get_future();
futures.push_back(f);
boost::thread t{ &Test::histograms, p }; // [1]
t.detach(); // to be compatible with C++11
}