简体   繁体   English

C ++中的最大线程数

[英]Maximum number of threads in C++

Trivia 琐事

Usually, when I want to write a multi-threaded program in C++, I ask the hardware regarding the number of supported concurrent threads as shown in what follows: 通常,当我想用​​C ++编写多线程程序时,我会问硬件有关支持的并发线程的数量,如下所示:

unsigned int numThreads = std::thread::hardware_concurrency();

This returns the total number of supported concurrency. 这将返回支持的并发总数。 Hence, if we have 2 CPUs each of which can support 12 threads, numThreads will be equal to 24. 因此,如果我们有2个CPU,每个CPU可以支持12个线程,则numThreads将等于24。

Problem 问题

Recently I used numactl to enforce a program to run on ONE CPU ONLY. 最近我使用numactl强制执行程序只在一个CPU上运行。

numactl -N 1 ./a.out

The problem is that std::thread::hardware_concurrency() returns 24 even when I run it with numactl -N 1 . 问题是,即使我用numactl -N 1运行它, std::thread::hardware_concurrency()也会返回24。 However, under such settings the output of nproc is 12. 但是,在这样的设置下, nproc的输出为12。

numactl -N 1 nproc --> output = 12

Question

Perhaps std::thread::hardware_concurrency() is not designed to support such a scenario. 也许std::thread::hardware_concurrency()不是为支持这种情况而设计的。 That's not my concern. 那不是我关心的问题。 My question is, what is the best practice to get the supported number of threads when I want to run my program with numactl . 我的问题是,当我想用numactl运行我的程序时,获得支持的线程数的最佳做法是什么。

Further information 更多信息

In case you haven't dealt with numactl , it can be used to run a process using a NUMA policy. 如果您还没有处理numactl ,它可以用于使用NUMA策略运行进程。 For example, you can use it to enforce your program to be ran on one CPU only. 例如,您可以使用它来强制您的程序仅在一个CPU上运行。 The usage for such a case is shown above. 这种情况的用法如上所示。

You'll have to use OS specific calls to inquire about the limitations that it imposes on your process. 您必须使用特定于操作系统的调用来查询它对您的进程施加的限制。

hardware_concurrency potentially returns a hint to the number of threads supported (by your hardware), or may return 0. The OS can limit your process to fewer threads than this number (or could potentially use more), whether using tools like numactl , normal scheduling, or some other means. hardware_concurrency可能会返回一个提示支持的线程数(由您的硬件提供),或者可能返回0.操作系统可以将您的进程限制为比此数量更少的线程(或者可能使用更多),无论是使用numactl工具,还是正常调度或其他一些手段。 There is always the possibility that some process or user will change the allowable CPU set, which can effect the available concurrency. 某些进程或用户总是有可能更改允许的CPU集,这可能会影响可用的并发性。 A typical C++ program is not expected to have to concern itself with these details, particularly since changes in the number of available threads are often transient. 预计典型的C ++程序不必关注这些细节,特别是因为可用线程数量的变化通常是短暂的。

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

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