CPP多线程实现并行计算

#include <iostream>
#include <mutex>
#include <future>
#include <thread>
#include <chrono>
#include <vector>
#include <cstdlib>
using namespace std;
#define COUNT 5000000
long long  add(vector <long long >*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_guard<mutex>lckg(m);//锁定
		cout <<"线程ID:"<< this_thread::get_id() <<"	count="<<count<<"	sum="<<sum<< endl;
	}
	return sum;
}
void main()
{
	vector<long long>myint(COUNT);//开辟数组大小
	for (int i = 0; i < COUNT; i++)//填充数据  赋值
	{
		myint[i] = (i+1)%1000;//限定数据范围 0~999
		//cout << myint[i] << "	";
	}
	//future < vector<long long>>abc ;
	vector<future<long long >>result;
	//实现并行计算 获取CPU核心个数   创建线程必须为CPU核心的个数
	long long  cpus = thread::hardware_concurrency();
	cout << "cpu核心个数:" << cpus << endl;

	//启动线程   存储结果   使用线程分块
	for (long long i = 0; i < cpus * 2; i++)
	{
		//<span style="font-family: Arial, Helvetica, sans-serif;">//线程切割     </span>线程分块
		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();
}


更多资料 · 微信公众号搜索【CTO Plus】关注后,获取更多,我们一起学习交流。

关于公众号的描述访问如下链接


关于Articulate“做一个知识和技术的搬运工。做一个终身学习的爱好者。做一个有深度和广度的技术圈。”一直以来都想把专业领域的技https://mp.weixin.qq.com/s/0yqGBPbOI6QxHqK17WxU8Q

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SteveRocket

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值