Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#4.0 Parallel
Why is not The answer same following? Why is not The answer same following?
 
Normal coding :
for (long i = 1; i <= 5; i++)
 {
   sum = sum * i;
 }

Parallel Coding :

Parallel.For(1, 5, delegate(int i){ sum = sum * i; });
result of parallel=24
result of Normal=120
why ?
Posted 3-Dec-11 11:08am
Edited 3-Dec-11 11:21am
v2
Comments
Monjurul Habib at 3-Dec-11 16:22pm
   
Edited: Code block.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

In the parallel for loop the loop size is not inclusive to the loop where as in normal for loop the loop size included. Take look at for detail for Parallel Programming[^] MSDN article.
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

Hi,
 
You have tried to parallize a calculation where the result of one iteration is dependent on the previous. If the sum was not used in the multiplication the value would not be transferred to the next iteration.
You can only parallize stuff where iterations have no relation to each other.
 
Your result may vary on the machine you run it on when you do it like this, the sum value needs closure th make sure it's not effected outside the loop.
 
Hope this helps.
 
Regards, AT
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

The reason is,,,, the value of sum was changed from the 1st for loop and used again in the second block of codes. Try using 2 different variables like: sum1 and sum2
 
Regards,
Eduard
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 565
1 Kornfeld Eliyahu Peter 409
2 Maciej Los 369
3 DamithSL 196
4 OriginalGriff 188
0 OriginalGriff 6,353
1 DamithSL 4,854
2 Maciej Los 4,466
3 Kornfeld Eliyahu Peter 4,058
4 Sergey Alexandrovich Kryukov 3,897


Advertise | Privacy | Mobile
Web04 | 2.8.141220.1 | Last Updated 3 Dec 2011
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100