Parallel Programming-Paralle.For & amp; ForEach, parallelprogramming

Source: Internet
Author: User

Parallel Programming-Paralle.For & ForEach, parallelprogramming

This article describes Parallel. For and Parallel. ForEach. Parallel. For is a Parallel replacement solution for a For loop with a common step of 1. Parallel. ForEach uses the Parallel method of foreach For Loop Based on the set. The main content is as follows:

1. Example of Parallel. For1.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 run

Time has been greatly improved.

Ii. Skip loop: Break vs Stop

You can use the break/Stop keyword to exit the loop for serial execution. Parallel. For can exit or stop the loop through 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 is the first parameter (optional) of the loop body, and the first parameter is I.

Iii. Differences between Break and Stop

When the Break is executed, all operations smaller than the current index (I) will be completed, and the iteration later than the current index will not start (not stop executing) -"will continue execution if it has already started.

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

Further note: When the loop with index 8 starts to be executed, the loop with index 1, 2, and 3 may not have started. Therefore, when Break is executed (index is 8), the execution of 1, 2, and 3 is not completed.

For example, in the above example, when I = 8, run break. The above code is executed:

0-7 is executed, and 8 is printed out (may be 10, 9), because the corresponding cycle of index8 has started before break.

When the Stop operation is executed, Parallel ends the loop at the fastest speed. If the loop operation is earlier than the index of the current stop operation, the unstarted loop operation is not executed. So Stop can end iteration more quickly than Break.

Calling the Stop method indicates that any iterations of the loop that have not yet started need not be run. it provides tively 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 returnTrueFor any iteration of the loop that is still executing. This is Special useful for long-running iterations, which can check the IsStopped property and exit early if its value isTrue.

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

Break and Stop cannot be used at the same time, and an exception is thrown.

4. Continue function.

Parallel. For does not have the Continue keyword. You can simply use Return to complete the Continue function.

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

Parallel. For has the ParallelOptions attribute. You can specify CancellationSourceToken and MaxDegreeOfParallelism (maximum concurrency)

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

This article has been explaining how Parallel. For is applicable to Parallel. ForEach. However, Parallel. ForEach has a special feature. Partitioner.

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

The code above divides 1000000 times into two 50000 for parallel execution, but each 50000 (range) is serialized and self-executed. The above program prints two "IN Parallel ".

6.2 description

Why use Partitioner? The use of parallel development has two major sales features: one is thread scheduling and the other is the scheduling proxy method. If the loop body itself has a small overhead, a large number of threads will not be worth the candle: the scheduling overhead is greater than the performance improvement brought about by the use of parallelism. The preceding example shows that Partitioner reduces the number of parallel operations and increases the volume of the loop body. Achieves coordination between parallel and scheduling overhead.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.