The summation of Paralle.

Source: Internet
Author: User

. NET4 adds the parallel mechanism-the so-called parallel mechanism is to open up several threads for computing at the same time. Because these threads are independent from each other, it is very simple to perform some distributed tasks (such as different jobs, however, it is not so easy to summarize these processing results. Here is a very simple example (1 ~ The sum of 1000 ).
If you try to use the following code calculation, I'm afraid it will surprise you!
[C #]
Int sum = 0;
Parallel. For (0, 1000, I => {sum + = I ;});
[VB. NET]
Dim sum As Integer = 0
Parallel. [For] (0, 1000, Function (I)
Sum + = I)
The reason is that. NET will open up some threads by default for "sum + = I" calculation at the same time. Therefore, because sum is used by these threads at the same time, it is often because one thread has not finished processing, and another thread is involved again, so it is naturally unable to get the correct result.
There are many solutions to this problem:
[1] decomposition method:
The so-called decomposition method is proposed for the criticism that "the same variable" is "shared" by different threads. -- That is to say, set 1 ~ 1000 sum is divided into several blocks for processing (equal to allocating different memory to each thread ). Finally, sum up the results of distributed computing. The result is as follows:
[C #]
Int [] numbers = Enumerable. Range (1, 1000). ToArray ();
Int [] values = new int [4];
Int sum = 0;
Parallel. For (0, 4, I => {values [I] = new Program (). GetTotal (I * 250,250, numbers );});
Sum = values. Sum ();
Console. WriteLine (sum );
[VB. NET]
 
Dim numbers As Integer () = Enumerable. Range (1, 1000). ToArray ()
Dim values As Integer () = New Integer (3 ){}
Dim sum As Integer = 0
Parallel. [For] (0, 4, Function (I)
Values (I) = New Program (). GetTotal (I * 250,250, numbers ))
Sum = values. Sum ()
Console. WriteLine (sum)
 
[2] use static variables
Static variables themselves have the ability to "Synchronize" (This example can also be seen in a simple factory ). The Code is as follows:
[C #]
 
Public class Program
{
Static int sum = 0;
Static void Main (string [] args)
{
Parallel. For (1, 1001, I => {sum + = I ;});
Console. WriteLine (sum );
}
}
 
[VB. NET]
 
Public Class Program
Shared sum As Integer = 0
Private Shared Sub Main (args As String ())
Parallel. [For] (1, 1001, Sub (I)
Sum + = I)
Console. WriteLine (sum)
End Sub
End Class
 
[3] Using volatile variables (generally, in order to optimize the performance, the compiler often copies common variables to registers and then directly operates on the registers, after the operation is completed, write it back to the original memory. Multithreading will cause the variables in the register to be not synchronized, so the results are not correct. Volatile tells the compiler to read the number from the memory directly, instead of copying it to the register for processing ):
[C #]
 
Public class Program
{
Volatile int sum = 0;
Public void ShowResult ()
{
Parallel. For (1, 1001, I => {sum + = I ;});
Console. WriteLine (sum );
}

Static void Main (string [] args)
{
Program p = new Program ();
P. ShowResult ();
}
}
 
[VB. NET, because VB. NET does not have this feature, Use Thread. VolitaleRead to accumulate the latest value each time]
 
Public Class Program
Dim sum As Integer = 0
Public Sub ShowResult ()
Parallel. For (1, 1001, Sub (I)
Thread. VolatileRead (sum) 'always reads the latest value
Sum = sum + I
Thread. Sleep (2)
End Sub)
Console. WriteLine (sum)
End Sub

Public Shared Sub Main (args As String ())
Dim p As New Program ()
P. ShowResult ()
End Sub
End Class
 
[4] Use lock (lock a variable, and then release the variable automatically after the thread operation is completed. Another thread comes in for the operation ...... ):
[C #]
 
Public class Program
{
Int sum = 0;
Public void ShowResult ()
{
Object obj = new object ();
Parallel. For (1, 1001, I => {lock (obj) {sum + = I; Thread. Sleep (10 );}});
Console. WriteLine (sum );
}

Static void Main (string [] args)
{
Program p = new Program ();
P. ShowResult ();
}
}
 
[VB. NET]
 
Public Class Program
Private sum As Integer = 0
Private obj As New Object
Public Sub ShowResult ()
Dim obj As New Object ()
Parallel. For (1, 1001, Sub (I)
SyncLock obj
Sum = sum + I
End SyncLock
End Sub)
Console. WriteLine (sum)
End Sub
End Class

Module M
Sub Main ()
Dim p As New Program
P. ShowResult ()
End Sub
End Module
 
[5] use the InternLock function:
[C #]
 
Public class Program
{
Int sum = 0;
Public void ShowResult ()
{
Parallel. For (1, 1001, I => {Interlocked. Add (ref sum, I );});
Console. WriteLine (sum );
}

Static void Main (string [] args)
{
Program p = new Program ();
P. ShowResult ();
}
}
 
[VB. NET]
 
Public Class Program
Private sum As Integer = 0
Public Sub ShowResult ()
Parallel. [For] (1, 1001, Sub (I)
Interlocked. Add (sum, I)
End Sub)
Console. WriteLine (sum)
End Sub

Shared Sub Main (args As String ())
Dim p As New Program ()
P. ShowResult ()
End Sub
End Class

 

 

From Serviceboy

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.