控制對 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
之前發生。