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++