《我的都一本c++书》学习笔记:PPL之多线程

一、PPL是微软Visual C++ 2010中提供的一个简化多线程应用程序开发的编程模型。PPL建立在并发运行时的调度和资源管理组件之上。它在代码与底层线程机制之间插入了一层抽象层,提供支持并发的泛化、类型安全的算法和并行容器。

PPL支持如下特性:

1、并行算法:并行作用于一组数据的泛化算法

2、并行任务:一个可并行执行几个工作单位的机制

3、并行容器和对象:可安全的并发存取其元素的泛化的容器


二、并行的几种算法:

1、parallel_for算法

其对常用的for循环语句进行并行化。

// 1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
#include <ppl.h>
#include <time.h>

using namespace std;
using namespace Concurrency;


int _tmain(int argc, _TCHAR* argv[])
{
	int a[10];
	for (int i = 0; i < 10; ++i)
	{
		a[i] = i;
	}
	
	//标准for循环
	clock_t start1 = clock();
	for (int j = 0; j < 10; ++j)
	{
		cout<<a[j]<<endl;
	}
	clock_t end1 = clock();

	cout<<"所需时间为:"<<end1-start1<<"毫秒"<<endl;

	cout<<"Concurrency runtime"<<endl;
	clock_t start2 = clock();
	parallel_for(0, 10, 1, 
		[&]( int i )
	{
		
		cout<<a[i]<<endl;
	});
	clock_t end2 = clock();
	cout<<"所需时间为:"<<end2-start2<<"毫秒"<<endl;

	return 0;
}

2、parallel_for_each()算法

前面是对for循环,如果是对STL容器中的数据,通常使用的是for_each()算法访问容器中的各个元素。但这些访问都是串行,所以parallel_for_each()则可以并行处理容器中的数据。


3、parallel_invoke()算法

其算法可以接受2到10个函数对象作为参数,也就是各个线程的线程函数。


你可能感兴趣的:(《我的都一本c++书》学习笔记:PPL之多线程)