有没有办法显式设置/限制 std::async
和相关类使用的并行度(= 独立线程数)?
Perusing the thread support library没有发现任何有希望的东西。
据我所知,std::async
实现(通常?)在内部使用线程池。是否有标准化的 API 来控制它?
对于背景:我在一个设置(共享集群)中,我必须手动限制使用的内核数量。如果我没有做到这一点,负载共享调度程序就会出现问题,我就会受到惩罚。特别是,std::thread::hardware_concurrency()
没有任何有用的信息,因为物理内核的数量与我所受的约束无关。
这是一段相关的代码(在具有并行性 TS 的 C++17 中,可能会使用 parallel std::transform
编写):
auto read_data(std::string const&) -> std::string;
auto multi_read_data(std::vector<std::string> const& filenames, int ncores = 2) -> std::vector<std::string> {
auto futures = std::vector<std::future<std::string>>{};
// Haha, I wish.
std::thread_pool::set_max_parallelism(ncores);
for (auto const& filename : filenames) {
futures.push_back(std::async(std::launch::async, read_data, filename));
}
auto ret = std::vector<std::string>(filenames.size());
std::transform(futures.begin(), futures.end(), ret.begin(),
[](std::future<std::string>& f) {return f.get();});
return ret;
}
从设计的角度来看,我希望 std::execution::parallel_policy
类(来自 parallelism TS)允许指定(事实上,这就是我在我为硕士论文设计的框架)。但事实并非如此。
理想情况下,我想要一个适用于 C++11 的解决方案,但如果有适用于更高版本的解决方案,我仍然想了解它(尽管我不能使用它)。
最佳答案
没有。 std::async
是不透明的,您无法控制它对线程、线程池或其他任何东西的使用。事实上,您甚至不能保证它会使用一个线程——它也可能在同一个线程中执行(可能,请注意下面的@T.C.评论),并且这样的实现仍然是一致的。
C++ 线程库从来不应该处理线程管理的操作系统/硬件细节的微调,所以我担心,在您的情况下,您将不得不自己编写代码以获得适当的支持,可能使用操作系统提供的线程控制原语.
关于c++ - 使用 std::async 控制并行度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45106657/