Click here to Skip to main content
15,891,204 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Why is not The answer same following? Why is not The answer same following?

Normal coding :
C#
for (long i = 1; i <= 5; i++)
 {
   sum = sum * i;
 }


Parallel Coding :

C#
Parallel.For(1, 5, delegate(int i){ sum = sum * i; });

result of parallel=24
result of Normal=120
why ?
Posted
Updated 3-Dec-11 10:21am
v2
Comments
Monjurul Habib 3-Dec-11 16:22pm    
Edited: Code block.

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.
 
Share this answer
 
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
 
Share this answer
 
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
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900