C++多线程教程(三)利用多线程实现加速

简介

在前期基础知识储备以后,让我们正式进入利用多线程实现程序加速的环节

基本思想

将原始计算过程拆分为多个过程。例如计算五亿次加法过程。我们可以将其分为两个过程,从零加到两万五,再从两万五加到五万。

程序实现

下面的程序分别展示用两个线程和单个线程实现五亿次加法过程。measure测量时间函数已经在上一章节中详述,不再重复。

int main() {
          
   
	long times = 500000000;
	measure([times]() {
          
              //双线程
		long ans1 = 0, ans2 = 0;
		thread t1 = thread(NumberAdd, 0, times / 2, ref(ans1));
		thread t2 = thread(NumberAdd, times / 2, times, ref(ans2));
		t1.join();
		t2.join();
		cout << "result of two treads: " << ans1 + ans2 << endl;
		}
	);
	
	measure([times]() {
          
              //单线程
		long ans = 0;
		NumberAdd(0, times, ans);
		cout << "result of single treads: " << ans<< endl;
		}
	);
}
void NumberAdd(long start, long end, long &ans) {
          
   
	int sum = 0;
	for (long i = start; i < end; i++) 
		sum = sum + 1;
	ans = sum;
}

程序结果如下

result of two treads: 500000000
PerformTest total time: 0.339524
result of single treads: 500000000
PerformTest total time: 0.651237

我们可以看到,利用双线程速度明显比单线程快了将近一倍。如果我们电脑不止2个核,我们可以拆分为更多线程执行,得到更短的时间。

进阶:使用feature类批量获取结果

以上代码是通过引用传递 ans 来获取结果,接下来我将介绍更加便捷的一种获取结果的方式——feature类。

基本语法

通过使用 async 函数,启动线程,返回一个 future 类,调用 __get __ 函数得到结果(阻塞式:执行完才能得到处理结果)。async 函数的使用方式与thread类似。

inline future<__async_result_of<_Fn, _Args...>>
async(_Fn&& __fn, _Args&&... _args)

示例代码

#include<future>                  //要增加一个future头函数
int main() {
          
   
	long times = 500000000;
	
	measure([times]() {
          
              //方括号捕捉外部变量times
		int K = 5;
		vector<future<long>> t_res;
		t_res.reserve(K);
		for (int i = 0; i < K; i++)
		{
          
   	
			t_res.push_back(async(NumberAdd, times/K*i, times / K * (i+1) ) );
		}
		long ans = 0;
		for (int i = 0; i < K; i++)
		{
          
   
			ans += t_res[i].get();
		}
		cout << ans << endl;
		}
	);
}

程序结果如下 分为五个线程的执行结果是单线程的四分之一,是不是加快了很多呢。

500000000
PerformTest total time: 0.160804

参考资料

链接: . 链接: .

经验分享 程序员 微信小程序 职场和发展