C++11使用标准库获取CPU物理核心数、动态创建线程

在本文中,将使用C++11标准线程库来获取CPU的物理核心数,并动态的创建和使用线程;

示例代码

#include <iostream>
#include <thread>
#include <string>

void _call(const std::string message) {

	/*
		std:cout 线程不同步/不安全
		std::cout << message << std::endl;
	*/

	printf("%s\n", message.c_str());

}

int main(int argc, char* argv[]) {

	//获取CPU核心
	int concurrency = std::thread::hardware_concurrency();

	std::cout << "hardware concurrency:" << concurrency << std::endl;

	std::thread* workers = new std::thread[concurrency];

	for (int i = 0; i < concurrency; i++) {

		std::string msg;
		msg = "id - " + std::to_string(i);

		workers[i] = std::thread(_call,msg);
	}

	for (int i = 0; i < concurrency; i++) {
		workers[i].join();
	}

	delete[] workers;

	_call("done");
}

运行效果

c++ thread

编译命令

代码保存为main.cpp

gcc -o app.exe main.cpp -lstdc++
分类: 计算机技术
推荐阅读:
Python this模块的加密原理 this模块的代码(this模块位于Python安装目录/lib下)。定义了2个变量;字符串s和字典d(被定义两次);s很明显是一段密文,d则是密码字典,key和value对应的是密文和原文;chr((i&#43;13)%26 &#43;c) 则是加密算法,其原理是通过向字典d写入KEY为字符A~Z,VALUE为加密后的字符。然后通过字典遍历的方法,匹配出正确的字符。
pm.max_children的作用 "pm.max_children" 是一个 PHP-FPM 配置选项,用于指定每个 PHP-FPM 进程池中最大的子进程数。它控制着 PHP-FPM 进程池的大小和性能表现。
C语言中 i++ 和 ++i 的区别 在C语言中,++ 运算符也叫递增运算符,只需要一个操作数,属于一元运算符;本文将讨论前缀++运算符和后缀++运算符的区别,以及符号优先级的问题;
Pyside6.QtWidgets.QApplication详细教程 PySide6.QtWidgets.QApplication类用于管理GUI应用程序的控制流和主要设置;
Python计算圆周率,精确到n位 本文将使用Python计算圆周率,可精确到n位,n值越大精度越高。
Python locals()函数 在 Python 中,locals() 是一个内置函数,用于返回当前作用域中的所有局部变量的字典。在函数内部,locals() 返回该函数的局部变量。在模块级别上,locals() 返回全局变量。