.net中的System.Threading命名空間的Interlocked類可以爲多個線程共享的變量提供原子操作。
經驗顯示,那些需要在多線程下被保護的資源通常是整型的,而這些被共享的整型值最常見的操作就是增加、減少。Interlocked類提供了一個專門的機制用於完成這些特定的操作。
下面的例子是一個沒有使用Interlocked類的操作:
class Program
{
static long counter = 1;
static void Main(string[] args)
{
System.Threading.Thread t1 = new System.Threading.Thread(f1);
System.Threading.Thread t2 = new System.Threading.Thread(f2);
t1.Start();
t2.Start();
t1.Join();
t2.Join();
System.Console.Read();
}
static void f1)
{
for (int i = 1; i <= 1000; i++)
{
counter++;
System.Console.WriteLine("Counter++ {0}", counter);
System.Threading.Thread.Sleep(10);
}
}
static void f2)
{
for (int i = 1; i <= 1000; i++)
{
counter--;
System.Console.WriteLine("Counter++ {0}", counter);
System.Threading.Thread.Sleep(10);
}
}
}
最後的結果counter的值爲2,如果我們是用單線程操作的話counter的值應該是1,下面的例子是使用Interlocked類的:
class Program
{
static long counter = 1;
static void Main(string[] args)
{
System.Threading.Thread t1 = new System.Threading.Thread(f1);
System.Threading.Thread t2 = new System.Threading.Thread(f2);
t1.Start();
t2.Start();
t1.Join();
t2.Join();
System.Console.Read();
}
static void f1()
{
for (int i = 1; i <= 5; i++)
{
Interlocked.Increment(ref counter);
System.Console.WriteLine("Counter++ {0}", counter);
System.Threading.Thread.Sleep(10);
}
}
static void f2()
{
for (int i = 1; i <= 5; i++)
{
Interlocked.Decrement(ref counter);
System.Console.WriteLine("Counter++ {0}", counter);
System.Threading.Thread.Sleep(10);
}
}
}
這次最後的結果是1。
在大多數計算機上,增加變量操作不是一個原子操作,需要執行下列步驟:
1、將實例變量中的值加載到寄存器中。
2、增加或減少該值。
3、在實例變量中存儲該值。(來自MSDN)