CPP多线程实现并行计算

#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
#define COUNT 5000000
long long  add(vector *arr, long long  start, long long count)
{
	static mutex m;//仅仅初始化一次
	int sum(0);//保存结果
	for (long long i = 0; i < count; i++)
	{
		sum += (*arr)[start+i];//根据下标  累加
	}
	{
		lock_guardlckg(m);//锁定
		cout <<"线程ID:"<< this_thread::get_id() <<"	count="<>abc ;
	vector>result;
	//实现并行计算 获取CPU核心个数   创建线程必须为CPU核心的个数
	long long  cpus = thread::hardware_concurrency();
	cout << "cpu核心个数:" << cpus << endl;

	//启动线程   存储结果   使用线程分块
	for (long long i = 0; i < cpus * 2; i++)
	{
		////线程切割     线程分块
		long long  batch_each = COUNT / (cpus * 2);
		if (i == cpus * 2-1)
		{
			batch_each = COUNT - COUNT / (cpus * 2)*i;//让最后一个线程承载多点
		}
		result.push_back(async(add,&myint,i*batch_each,batch_each));//压入数据
	}
	//分数据
	long long  lastresult(0);//最终结果
	//汇总数据
	for (long long i = 0; i < cpus * 2; i++)
	{
		lastresult += result[i].get();//累加
	}
	cout << "lastresult ="<< lastresult << endl;
	cin.get();
}
CPP多线程实现并行计算_第1张图片

你可能感兴趣的:(CPP多线程实现并行计算)