📅  最后修改于: 2023-12-03 14:59:51.589000             🧑  作者: Mango
hardware_concurrency()
函数在 C++11 中,可以使用 <thread>
头文件中的 std::thread::hardware_concurrency()
函数获取系统支持的最大线程数。
函数声明如下:
unsigned hardware_concurrency() noexcept;
该函数返回一个 unsigned
类型的整数,表示当前系统支持的最大线程数。如果无法获取该信息,则返回 0。
以下是一个简单的示例程序,演示了如何使用 hardware_concurrency()
函数获取最大线程数:
#include <iostream>
#include <thread>
int main() {
unsigned int num_cpus = std::thread::hardware_concurrency();
if (num_cpus == 0) {
std::cout << "无法获取系统支持的最大线程数" << std::endl;
} else {
std::cout << "系统支持的最大线程数为 " << num_cpus << std::endl;
}
return 0;
}
上述程序的输出结果类似于以下内容,但实际输出结果可能会因系统环境的不同而有所不同:
系统支持的最大线程数为 8
hardware_concurrency()
函数可以用来获取系统支持的最大线程数,从而在编写多线程程序时更好地管理线程数量,提高程序性能。