Use of parallel development--parallel-excerpt from the Web

Source: Internet
Author: User

With the advent of the multicore era, parallel development is increasingly demonstrating its power, and yards like ours no longer pay much attention to the implementation of the underlying thread and manual control,

To understand parallel development, you need to understand the next two concepts: "Hardware Threads" and "Software threads."

1. Hardware Threads

I believe everyone in the computer is more than dual-core, antique computers like me are dual-core, such a dual-core is called the physical core.

Hardware threads are also called logical cores, and we can see the Performance tab in Task Manager, as we know there are 2 hardware threads.

In general, a physical kernel corresponds to a logical kernel, such as my 2 to 2 here. Of course, if your CPU uses Hyper-Threading technology, then there may be 4 physical cores corresponding to

8 Hardware threads, there are now many servers have 8 hardware threads, the morning on the company's server to intercept a diagram.

We need to know that parallel development is about allocating tasks to these hardware threads to execute in parallel to achieve load and acceleration.

2. Software threads

I believe this is the most familiar, we know that the traditional code is serial, on a main thread, when we to achieve acceleration and open a lot of worker threads, these worker threads

This is the software thread.

OK, we know the basic concept is OK, in. NET 4.0, Microsoft has given us a new namespace: System.Threading.Tasks. There's a lot of fun in it.

Things, as the first article on the introduction under the most basic, the simplest parallel use.

One: the use of parallel

Below parallel there are three common methods Invoke,for and foreach.

1:parallel.invoke

This is the simplest and most concise parallelization of serial code.

1Class Program2 {3Staticvoid Main (String[] args)4 {5var watch = Stopwatch.startnew ();67 Watch. Start ();89 Run1 ();10Run2 ();12Console.WriteLine ("I am serial development, total time consuming: {0}\n", watch. Elapsedmilliseconds);14Watch. Restart ();16Parallel.Invoke (RUN1, Run2);18Watch. Stop ();20Console.WriteLine ("I am parallel development, total time consuming: {0}22 23 console.read ();  }25 26 static void Run1 () 27 {28 Console.WriteLine ( " I'm mission one, I'm running 3s29 thread.sleep (3000);  }31 32 static void Run2 () 33 {34 Console.WriteLine ( " I'm mission two, I ran 5s35 thread.sleep (5000);  }37}              

In this example, you can get two points of information:

First: A task can be broken down into multiple tasks, using the idea of divide and conquer.

Second: As far as possible to avoid the dependencies between sub-tasks, because the sub-task is executed in parallel, so there is no one who must be in front of, who must be in the post-regulation.

2:parallel.for

We know that there is also a for in the serial code, but that for does not use multicore, and paraller.for it uses all of the available hardware threads at the bottom level, depending on the health of the

Take advantage of the hardware thread, note here that the Parallel.For Walk is 1.

Here we demonstrate that inserting data into a thread-safe collection, of course, uses atomicity to achieve thread synchronization, which is more cost-efficient than the heavy-duty locking mechanism.

1Class Program2 {3Staticvoid Main (String[] args)4 {5for (Int J =1; J <4; J + +)6 {7 Console.WriteLine ("\ n {0} times comparison", j);89 concurrentbag<int> bag =New concurrentbag<Int> ();1011var watch = Stopwatch.startnew ();12Watch. Start ();1415for (int i =0; I <20000000; i++)16 {Bag. ADD (i);18}19Console.WriteLine ("Serial calculation: The collection has: {0}, Total time: {1}", bag. Count, watch. Elapsedmilliseconds);21stGC. Collect ();23 24 bag = new concurrentbag<int > (); 25 26 watch = Stopwatch.startnew (); 27 28 watch. Start (); 29 30 parallel.for (0, 20000000, I = 31 {32 bag. ADD (i); 33}); 34 35 Console.WriteLine ( " Parallel Computation: The set has: {0 }, total time-consuming: {1}36 37 GC. Collect (); 38 39} 40} 41}      

It can be seen that the effect of acceleration is more obvious.

3:parallel.foreach ForEach is unique is the data can be partitioned, each cell in the implementation of serial computing, zoning using partitioner.create implementation.

 Class Program {Staticvoid Main (String[] (args) {for (Int J =1; J <4; J + +) {Console.WriteLine ("\ n {0} times comparison", j);
concurrentbag<int> bag =New concurrentbag<int> ();
var watch = Stopwatch.startnew ();
Watch. Start ();
for (int i = 0; I < 3000000; i++) {b Ag. ADD (i);
Console.WriteLine (" Serial calculation: The collection has: {0}, total time consuming: {1} ", bag. Count, watch. Elapsedmilliseconds);
GC. Collect ();
Bag = new concurrentbag<int> ();
Watch = Stopwatch.startnew ();
Watch. Start ();
Parallel.ForEach (partitioner.create (0, 3000000), i + = {for (int m = i. Item1; M < i.item2; m++) {bag. ADD (m); } });
Console.WriteLine ( " Parallel Calculation: The collection has: {0}, total time consuming: {1}", bag. Count, watch. Elapsedmilliseconds);
GC. Collect ();
}}}
/span>

Here is still to say: Partitioner.create (0, 3000000).

First: We want to partition the range is 0-3000000.

Second: We certainly want to know how many districts the system has assigned us? Unfortunately, this is the internal coordination of the system, do not have the right to tell us, of course, the system does not object to our own designated partition number,

Here you can use the sixth overload of Partitioner.create, such as this: Partitioner.create (0, 3000000, Environment.processorcount),

Because Environment.processorcount is able to get the current number of hardware threads, there are 2 of zones open.

Let's share some of the doubts we might have in parallel computing.

<1> How do I exit the parallel loop halfway?

Yes, in the serial code we're done with a break, but parallelism isn't that simple, but it doesn't matter, in the delegate parameter of the parallel loop, a

ParallelLoopState, this example provides the break and stop methods to help us implement.

Break: Of course this is the notification parallel computation as soon as the exit loop, such as parallel computing is iterating 100, then after break the program will also iterate all less than 100.

Stop: This is not the same, such as the iteration of the 100 suddenly encountered stop, then it doesn't matter, directly exit.

Here's an example of exiting a loop when iterating to 1000

1Class Program2 {3Staticvoid Main (String[] args)4 {5var watch = Stopwatch.startnew ();67 Watch. Start (); 8  9 Concurrentbag<int> bag = new Concurrentbag<int> ();  Ten 11 parallel.for (0, 20000000, (I, State) =>12 {13 if (bag. Count = = 1000) 14 {15 state. Break (); 16 return; }18 bag. ADD (i); 19}); 20 21 Console.WriteLine ( "22 23}24}         

<2> How do I handle exceptions thrown in parallel computing?

The first task is the parallel computation, the processing process may produce more than n exceptions, then how to get these exceptions? Ordinary exception do not get an exception, but aggregateexcepation that are born in parallel can get a set of exceptions.

Class Program {Staticvoid Main (string[] args)         {try {Parallel.Invoke (Run1, Run2); } catch (AggregateException ex) {foreach (var single  in ex. InnerExceptions) {Console.WriteLine (single). Message); }} 
Console.read ();}
static void Run1 () {thread.sleep (3000); throw new Exception ( " I am the exception thrown by task 1 static void Run2 () {thread.sleep (5000);
throw new Exception ( " I am the exception thrown by Task 2

<3> Parallel Computing can I leave a hardware thread out?

By default, the underlying mechanism uses as much hardware threads as possible, but the advantage of using manual designations is that we can measure speedup in the case of 2,4,8 hardware threads.

Class program     {         void Main (string[] args)         {             new concurrentbag<int> () ;
New ParallelOptions ();
specifies that the number of hardware threads used is 1 options. Maxdegreeofparallelism = 1;
Parallel.For (300000, options, i + = bag. ADD (i); });
Console.WriteLine (" Parallel Computing: The collection has: {0}", bag.) Count);
} }

Use of parallel development--parallel-excerpt from the Web

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.