我正在尝试用线程池替换std::async
的用法。目前,我正在尝试使用boost::executors::basic_thread_pool
。然而,问题是我有对象,这些对象不是线程安全的。
一个天真的解决方案就是制作大量的副本,例如:
boost::executors::basic_thread_pool thread_pool;
void do_work() {
const auto computer = slow_creation();
std::vector<boost::future<result_t>> results;
for (int i = 0; i < 1000000; ++i)
{
results.push_back(boost::async(thread_pool, computer.deep_copy()));
}
// wait to complete
// use results
}
我希望它看起来像这样:
boost::executors::basic_thread_pool thread_pool;
void do_work() {
const auto computer = slow_creation();
std::vector<boost::future<result_t>> results;
for (int i = 0; i < 1000000; ++i)
{
results.push_back(boost::async(thread_pool,
[] {
thread_local (but_not_global) copy = computer.deep_copy();
return copy();
}
));
}
// wait to complete
// use results
}
如何使用Boost或任何其他库执行此操作?我更喜欢基于库的解决方案,它具有良好的线程池实现。