Parallel Programming-Parallel.Invoke

本文主要介绍Parallel.Invoke的使用。

一、使用例子

 class ParallelInvoke
    {
        public void Action1()
        {
            Thread.Sleep(3000);
            Console.WriteLine("in action1");
        }

        public void Action2()
        {
            Thread.Sleep(3000);
            Console.WriteLine("in action2");
        }

        public void ParallelAction()
        {
            Parallel.Invoke(() => Action1(), () => Action2());
        }
    }
 class Program
    {
        static void Main(string[] args)
        {
            var stopwatch = Stopwatch.StartNew();
            stopwatch.Start();
            new ParallelInvoke().ParallelAction();
            Console.WriteLine(stopwatch.ElapsedMilliseconds);
            Console.Read();
        }
    }

二、 运行截图

上面的action1和action2如果并行执行至少需要3000*2毫秒,但是使用Invoke,内部并行执行,时间减半。

三、 分析

Parallel.Invoke是最简单的并行编程模型,用于并行执行多个互不相干的方法。有几点需要注意

  1. 只有当所有的Action执行完成后Invoke才会返回(WaitAll)
  2. 在执行过程中有其中一个Action发生异常,Invoke不会马上抛出异常,而是等所有的Action完成以后再次抛出异常

四、one more thing

4.1 MaxDegreeOfParallelism

Parallel.Invoke可以通过指定ParallelOption指定最大并行数量。

    public void ParallelAction()
        {
            Parallel.Invoke
            (
                new ParallelOptions()
                {
                    MaxDegreeOfParallelism = 1,
                },
                () => Action1(),
                () => Action2()
            );
        }

上面的代码设置成了1,其实就是串行执行了。

执行时间如下。

4.2 CancellationSourceToken

同样可以通过ParallelOption指定CancellationSourceToken,多个并行任务之间可以协调取消

   class ParallelInvoke
    {
        public void Action1(CancellationTokenSource cts)
        {
            cts.Cancel();
            Thread.Sleep(3000);
            Console.WriteLine("in action1");
        }

        public void Action2(CancellationTokenSource cts)
        {
            if (cts.IsCancellationRequested)
            {
                return;
            }
            Thread.Sleep(3000);
            Console.WriteLine("in action2");
        }

        public void ParallelAction()
        {
            CancellationTokenSource cts = new CancellationTokenSource();

            Parallel.Invoke
            (
                new ParallelOptions()
                {
                    CancellationToken = cts.Token,
                },
                () => Action1(cts),
                () => Action2(cts)
            );
        }
时间: 2024-10-12 22:36:37

Parallel Programming-Parallel.Invoke的相关文章

CUDA Intro to Parallel Programming笔记--Lesson 1 The GPU Programming Model

1.  3 traditional ways computes run faster Faster clocks More work/clock cycle More processors 2. Parallelism A high end Gpu contains over 3,000 arithmatic units,ALUs, that can simultanously run 3,000 arithmetic operations. GPU can have tens of thous

Intro to Parallel Programming课程笔记001

Intro to Parallel Programming How do you dig a hole faster? GPU理念 很多很多简单计算单元: 清洗的并行计算模型: 关注吞吐量而非延迟: CPU: HOST GPU:DEVICE A Typical GPU Program 1,CPUallocates(分配) storage on GPU  cuda Malloc 2,CPUcopies input data from CPU-GPU          cuda Memcpy 3,C

Samples for Parallel Programming with the .NET Framework

The .NET Framework 4 includes significant advancements for developers writing parallel and concurrent applications, including Parallel LINQ (PLINQ), the Task Parallel Library (TPL), new thread-safe collections, and a variety of new coordination and s

Concurrent and Parallel Programming

What's the difference between concurrency and parallelism? Explain it to a five year old. Concurrent = Two queues and one coffee machine. Parallel = Two queues and two coffee machines. Tagged:   concurrency      parallel      programming http://joear

Notes of Principles of Parallel Programming - partial

0.1 TopicNotes of Lin C., Snyder L.. Principles of Parallel Programming. Beijing: China Machine Press. 2008. (1) Parallel Computer Architecture - done 2015/5/24(2) Parallel Abstraction(3) Scable Algorithm Techniques(4) PP Languages: Java(Thread), MPI

Notes of Principles of Parallel Programming: Peril-L Notation

Content 1 syntax and semantic 2 example set 1 syntax and semantic 1.1 extending C Peril-L notation stands on the shoulder of C. 1.2 parallel threads forall(<intVar in (<index range specification>)){ <body> } 1.3 synchronized and coordinatio

【2014-11-23】Heterogeneous Parallel Programming &ndash; Section 1

Latency devices(CPU cores) Throughput devices(GPU cores) Use the best match for the job (heterogeneity in mobile SOC CPU: Latency Oriented Design Powerful ALU Reduced operation latency Large caches convert long latency memory accesses to short latenc

C#并行编程--命令式数据并行(Parallel.Invoke)---与匿名函数一起理解(转载整理)

命令式数据并行   Visual C# 2010和.NETFramework4.0提供了很多令人激动的新特性,这些特性是为应对多核处理器和多处理器的复杂性设计的.然而,因为他们包括了完整的新的特性,开发人员和架构师必须学习一种新的编程模型. 这一章是一些新的类.结构体和枚举类型,你可以使用这里来处理数据并行的场景.这章将为你展示怎样创建并行代码和描述与每个场景相关的新概念,而不是关注并发编程中的最复杂的问题.这样你将可以更加充分的理解性能改进. 开始并行任务  使用先前版本的.NET Frame

C#并行编程--命令式数据并行(Parallel.Invoke)

命令式数据并行   Visual C# 2010和.NETFramework4.0提供了很多令人激动的新特性,这些特性是为应对多核处理器和多处理器的复杂性设计的.然而,因为他们包括了完整的新的特性,开发人员和架构师必须学习一种新的编程模型. 这一章是一些新的类.结构体和枚举类型,你可以使用这里来处理数据并行的场景.这章将为你展示怎样创建并行代码和描述与每个场景相关的新概念,而不是关注并发编程中的最复杂的问题.这样你将可以更加充分的理解性能改进. 开始并行任务  使用先前版本的.NET Frame

PatentTips - Heterogeneous Parallel Primitives Programming Model

BACKGROUND 1. Field of the Invention The present invention relates generally to a programming model for a heterogeneous processor system. 2. Background Art With the success of programming models such as OpenCL and CUDA, heterogeneous computing platfo