简体   繁体   English

是否可以限制 C++ 17 并行`for_each`的线程数?

[英]Is it possible to limit threads count for C++ 17 parallel `for_each`?

I use std::for_each with std::execution::par to perform complex computation on huge input represented as vector of structures.我使用std::for_eachstd::execution::par对表示为结构向量的巨大输入执行复杂计算。 The computation doesn't need any delays related to hardware (network or disk IO for example), it is "just CPU" computation.计算不需要任何与硬件相关的延迟(例如网络或磁盘 IO),它是“仅 CPU”计算。 For me it looks logical that there are no sense to create more OS threads that we have hardware ones;对我来说,创建更多我们拥有硬件线程的操作系统线程似乎是合乎逻辑的。 however, Visual C++ 2019 creates in average 50 threads, and sometimes up to 500 ones even there are only 12 hardware threads.但是,Visual C++ 2019 平均创建了 50 个线程,有时即使只有 12 个硬件线程,也会创建多达 500 个线程。

Is there a way to limit parallel threads count to hardware_concurrency with std::for_each and std::execution::par , or the only way to create reasonable threads count is to use custom code with std::thread ?有没有办法使用std::for_eachstd::execution::par将并行线程数限制为hardware_concurrency ,或者创建合理线程数的唯一方法是使用自定义代码和std::thread

Is it possible to limit threads count for C++ 17 parallel for_each ?是否可以限制 C++ 17 并行for_each的线程数?

No, at least not in C++17.不,至少在 C++17 中没有。 However, there is a proposal for executors in a standard to come, which basically gives you the ability to influence the execution context (in terms of location and time) for the high-level STL algorithm interface:但是,在即将发布的标准中对executors器提出了建议,它基本上使您能够影响高级 STL 算法接口的执行上下文(在位置和时间方面):

thread_pool pool{ std::thread::hardware_concurrency() };
auto exec = pool.executor();
std::for_each(std::execution::par.on(exec), begin(data), end(data), some_operation);

Up to then, you have to either trust your compiler vendor that he knows what is best for the overall performance, as eg the developers of Visual Studio state :到那时,您必须相信您的编译器供应商,他知道什么对整体性能最有利,例如 Visual Studio state的开发人员:

Scheduling in our implementation is handled by the Windows system thread pool.我们实现中的调度由 Windows 系统线程池处理。 The thread pool takes advantage of information not available to the standard library, such as what other threads on the system are doing, what kernel resources threads are waiting for, and similar.线程池利用标准库不可用的信息,例如系统上的其他线程正在做什么,线程正在等待什么 kernel 资源,等等。 It chooses when to create more threads, and when to terminate them.它选择何时创建更多线程以及何时终止它们。 It's also shared with other system components, including those not using C++.它还与其他系统组件共享,包括不使用 C++ 的系统组件。

The other option would be to give up on solely relying on the standard library and use STL implementations which already feature the new proposal.另一种选择是放弃仅依赖标准库并使用已经包含新提案的 STL 实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM