本文主要介绍Parallel.For以及Parallel.ForEach。Parallel.For是普通步长为1的for循环的并行代替方案。Parallel.ForEach是以集合为基准进行循环的foreach的并行代替方案。主要以下内容:

  1. 使用例子
  2. 如何退出并行循环
  3. Break、Stop详细介绍
  4. Partitioner

一、Parallel.For

1.1 使用例子

 class ParallelFor
{
private void Action(int index)
{
Console.WriteLine(index);
Thread.Sleep(1000);
}
public void ParallelAction()
{
Parallel.For(0, 10, (i) => Action(i));
}
} class Program
{
static void Main(string[] args)
{
var stopwatch = Stopwatch.StartNew();
stopwatch.Start();
new ParallelFor().ParallelAction();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
Console.Read();
}
}

1.2 运行截图

时间有很大的提升。

二、跳出循环:Break vs Stop

串行执行的for可以使用break/Stop关键字直接退出循环。Parallel.For可以通过loopState进行退出或者停止循环。

 class ParallelFor
{
private void Action(int index)
{
Console.WriteLine(index);
Thread.Sleep(1000);
}
public void ParallelAction()
{
Parallel.For(0, 10, (i, loopState) =>
{
if (i == 8)
{
loopState.Break();//loopState.Stop()
}
Action(i);
});
}
}

LoopState是循环体的第一个参数(可选),第一个是i。

三、 Break和Stop的区别

Break执行时,小于当前的index(i)的操作都会保证执行完成,大于当前index的迭代不再开始(不是不再执行)-》已经开始的还是会继续执行。

Break indicates that no iterations after the current iteration should be run. It effectively cancels any additional iterations of the loop. However, it does not stop any iterations that have already begun execution.

进一步说明:当index为8的循环开始执行时,index为1,2,3的循环不一定已经开始了。所以当Break执行后(index为8),会保证没有执行的1,2,3执行完毕

比如上面的例子i==8时,进行break,上面的代码执行截图:

0-7保证执行,8也打印出来了(有可能还会有10,9),是因为index8对应的循环在break之前已经开始了。

Stop执行时,Parallel会用最快的速度结束循环,如果小于当前执行stop的index对应的循环操作还没有开始,则不会执行这些没有开始的。所以Stop比Break能够更加快速的结束迭代。

Calling the Stop method indicates that any iterations of the loop that have not yet started need not be run. It effectively cancels any additional iterations of the loop. However, it does not stop any iterations that have already begun execution.

Calling the Stop method causes the IsStopped property to return true for any iteration of the loop that is still executing. This is particularly useful for long-running iterations, which can check the IsStopped property and exit early if its value is true.

Stop is typically employed in search-based algorithms, where once a result is found, no other iterations need be executed.

Break和Stop不能同时使用,会有异常抛出。

四、Continue功能。

Parallel.For是没有Continue关键字的,简单的使用Return即可完成Continue的功能。

 public void ParallelAction()
{
Parallel.For(, , (i) =>
{
if (i == )
{
return;
}
Action(i);
});
}

五、ParallelOptions

Parallel.For通用有ParallelOptions这个属性,通过这个可以指定CancellationSourceToken和MaxDegreeOfParallelism(最大并发数)

 public void ParallelAction()
{
var cts = new CancellationTokenSource();
var option = new ParallelOptions()
{
CancellationToken = cts.Token,
MaxDegreeOfParallelism = 5
};
Parallel.For(, , option, (i) =>
{
if (cts.Token.IsCancellationRequested)
{
return;
}
Action(i);
});
}

六、Partitioner

本文一直在讲解Parallel.For上面的操作对于Parallel.ForEach都是通用的。但是Parallel.ForEach有个特殊功能。Partitioner。

6.1 例子

class ParallelForEach
{
public void ParallelAction()
{
int[] items = new int[];
Parallel.ForEach(Partitioner.Create(0, 100000, 50000), (range) =>
{
Console.WriteLine("IN Parallel");
for (var i = range.Item1; i < range.Item2; i++)
{
items[i] = i;
}
});
}
}

上面代码的把1000000次分成两个50000进行,这两个50000之间是并行执行的,但是在每个50000(range)是串行自己执行的。上面程序会打印出两"IN Parallel"。

6.2说明

为什么要使用Partitioner?使用并行开发有两大开销,一是线程调度,二是调度代理方法,如果循环体本身开销很小,大量使用线程会得不偿失:调度本身的开销大于使用并行带来的性能提升。上面的例子可以看出,使用Partitioner减少了并行的次数,增大了循环体的体积。达到了并行和调度开销的协调。

Parallel Programming-Paralle.For && ForEach的更多相关文章

  1. Notes of Principles of Parallel Programming - TODO

    0.1 TopicNotes of Lin C., Snyder L.. Principles of Parallel Programming. Beijing: China Machine Pres ...

  2. 4.3 Reduction代码(Heterogeneous Parallel Programming class lab)

    首先添加上Heterogeneous Parallel Programming class 中 lab: Reduction的代码: myReduction.c // MP Reduction // ...

  3. Task Cancellation: Parallel Programming

    http://beyondrelational.com/modules/2/blogs/79/posts/11524/task-cancellation-parallel-programming-ii ...

  4. Samples for Parallel Programming with the .NET Framework

    The .NET Framework 4 includes significant advancements for developers writing parallel and concurren ...

  5. Parallel Programming for FPGAs 学习笔记(1)

    Parallel Programming for FPGAs 学习笔记(1)

  6. Parallel Programming AND Asynchronous Programming

    https://blogs.oracle.com/dave/ Java Memory Model...and the pragmatics of itAleksey Shipilevaleksey.s ...

  7. Introduction to Multi-Threaded, Multi-Core and Parallel Programming concepts

    https://katyscode.wordpress.com/2013/05/17/introduction-to-multi-threaded-multi-core-and-parallel-pr ...

  8. Fork and Join: Java Can Excel at Painless Parallel Programming Too!---转

    原文地址:http://www.oracle.com/technetwork/articles/java/fork-join-422606.html Multicore processors are ...

  9. A Pattern Language for Parallel Programming

    The pattern language is organized into four design spaces.  Generally one starts at the top in the F ...

  10. parallel programming. this causual litery nots represents my recent progress in parallel programming in c#.It`s interesting.

    not to say extra words,let`s start the code. pasted below: using System; using System.Collections.Ge ...

随机推荐

  1. 【BZOJ2460】[BeiJing2011]元素 贪心+高斯消元求线性基

    [BZOJ2460][BeiJing2011]元素 Description 相传,在远古时期,位于西方大陆的 Magic Land 上,人们已经掌握了用魔法矿石炼制法杖的技术.那时人们就认识到,一个法 ...

  2. WebApi 中使用 Token

    1.登陆的时候根据用户信息生成Token var token = FormsAuthentication.Encrypt( new FormsAuthenticationTicket( , " ...

  3. 我的Android进阶之旅------> Android为TextView组件中显示的文本添加背景色

    通过上一篇文章 我的Android进阶之旅------> Android在TextView中显示图片方法 (地址:http://blog.csdn.net/ouyang_peng/article ...

  4. HDU 4824 Disk Schedule

    //

  5. Linux内核设计基础(九)之进程管理和调度

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/BlueCloudMatrix/article/details/30799225 在Linux中进程用 ...

  6. Linux系统BTC挖矿傻瓜教程

    [Linux系统BTC/比特币矿池挖矿方案一]cgminer矿池挖矿程序(Linux系统 比特币(BTC) 矿池挖矿/采矿/造币)cgminer矿池挖矿程序[查看这里有没有最新版]http://ck. ...

  7. LeetCode:区域和检索【303】

    LeetCode:区域和检索[303] 题目描述 给定一个整数数组  nums,求出数组从索引 i 到 j  (i ≤ j) 范围内元素的总和,包含 i,  j 两点. 示例: 给定 nums = [ ...

  8. gsub! 和 gsub

    ruby中带“!"和不带"!"的方法的最大的区别就是带”!"的会改变调用对象本身了.比方说str.gsub(/a/, 'b'),不会改变str本身,只会返回一个 ...

  9. Kattis - triangle 【数学】

    题意 求第N个迭代三角形 中 所有黑色三角形的周长的整数部分的位数 思路 该三角形的周长是 3^(n + 1)/ 2 ^ (n) 然后 可以用 long double 存下来 再求位数 就可以 AC ...

  10. 事件监听机制——列出指定目录内容、添加Dialog对话框

    事件监听机制理解与Dialog练习 利用Java语言,仿照我的电脑目录进行打开目录,输入文件路径,查看该路径下所有的文件,设置两个文本框,一个转到按钮,当点击转到按钮时,查看路径是否正确,若正确在第二 ...