控制对 Parallel.For 循环中变量的访问
using 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
是不够的,因为读取 - 修改 - 写入操作不是原子操作。线程将覆盖对 sum
的任何外部修改,这些修改在读取 sum
的当前值之后,但在将 sum + i
的修改值存储回 sum
之前发生。