简体   繁体   English

当我运行几个与CPU核心/线程数相匹配的线程时,每个线程是否会在一个单独的核心/线程上运行?

[英]When I run several threads that match the number of CPU core/threads, will each thread run on a separate core/thread?

The threads are launched by std::async(func) . 线程由std::async(func)

If not, how can I do it? 如果没有,我该怎么办?

The standard does not guarantee anything about on what cores/hyperthreads your threads will run. 该标准不保证您的线程将运行什么内核/超线程。 That is up to the operating system. 这取决于操作系统。

If you want to get platform specific (non-portable) then there are various API's to control thread affinity - like (for example) pthread_setaffinity_np on Linux. 如果您想获得特定于平台(非可移植),那么有各种API来控制线程关联性 - 例如Linux上的pthread_setaffinity_np But I'd personally advice just leaving it to the OS - it will most likely do a good job unless you have very specific needs. 但我个人建议将其留给操作系统 - 除非你有非常具体的需求,否则它很可能会做得很好。

In complement to Jesper's answer, the standard offers you the function std::thread::hardware_concurrency to get the number of hardware thread contexts (0 if information not available). 作为Jesper的答案的补充,该标准为您提供函数std::thread::hardware_concurrency以获取硬件线程上下文的数量(如果信息不可用,则为0)。

The way the threads are schedules is implementation dependent. 线程的调度方式取决于实现。 You can however be sure that your code has to share the cores with dozen of OS processes/services/daemons running with their own threads. 但是,您可以确保您的代码必须与使用自己的线程运行的十几个OS进程/服务/守护进程共享内核。

In view of your question, as you mention std::async(func) , it's worth to mention that you could force a launch policy, for example launch::async . 鉴于您的问题,正如您提到的std::async(func) ,值得一提的是您可以强制启动策略,例如launch::async Some implementations offer finer control, but again, the scheduling is implementation dependent. 一些实现提供更精细的控制,但同样,调度依赖于实现。

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

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