Controlling access to a variable in a Parallel.For loop
suggest changeusing System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static void Main( string[] args )
{
object sync = new object();
int sum = 0;
Parallel.For( 1, 1000, ( i ) => {
lock( sync ) sum = sum + i; // lock is necessary
// As a practical matter, ensure this `parallel for` executes
// on multiple threads by simulating a lengthy operation.
Thread.Sleep( 1 );
} );
Console.WriteLine( "Correct answer should be 499500. sum is: {0}", sum );
}
}
sum = sum + i is not enough without the lock, because the read-modify-write is not atomic. A thread can overwrite a change another thread made after it read sum and before it stored sum + i.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents