Why is not the same answer for following?
Normal coding:
long sum = 0;
for (long i = 1; i <= 10; i++)
{
long result = 1;
for (long j = 1; j <= i; j++)
{
result = result*j;
}
sum = sum + result;
}
Parallel Coding:
long sum = 0;
Parallel.For(1, 10, delegate(int i)
{
long result = 1;
Parallel.For(1, i, delegate(int j)
{
result = result*j;
});
sum = sum + result;
});
Please show me the right way
for (long i = 1; i <= 5; i++)
{
sum = sum * i;
}
and
Parallel.For(1, 5, delegate(int i)
{
sum = sum * i;
});
Result of parallel = 24
Result of normal = 120
The answer in parallel version is arbitrary because
sumandresultare accessed and modified by different threads. So what you should do is separating between computing each step and summing up results. To be able to sum up results correctly, you need to obtain a lock so that threads modifysumexclusively. One way to fix could be:Note that you rarely need two nested
Parallel.Forloops, because they often lead to bad performance. So oneParallel.Forloop at the outermost level and keeping innerforloops as they are is recommended. Also to obtain some speedup, you have to test with numbers much bigger than10.