只是爲了好奇,我製作了一個程序來測試InterLocked與.Net鎖定的性能。 事實證明,InterLocked版本比鎖定版本慢得多,有人請指出,如果我錯過了一些細節在這裏。 根據我的理解,聯鎖應該比鎖定表現要好得多。爲什麼InterLocked比鎖定慢?
public class TestB
{
private static readonly object _objLocker = new object();
private long _shared;
public void IncrLocked()
{
lock (_objLocker)
{
_shared++;
}
}
public void IncrInterLocked()
{
Interlocked.Increment(ref _shared);
}
public long GetValue()
{
return _shared;
}
}
class TestsCopy
{
private static TestB _testB = new TestB();
static void Main(string[] args)
{
int numofthreads = 100;
TestInterLocked(numofthreads);
TestLocked(numofthreads);
Console.ReadLine();
}
private static void TestInterLocked(int numofthreads)
{
Thread[] threads = new Thread[numofthreads];
for (int i = 0; i < numofthreads; i++)
{
Thread t = new Thread(StartTestInterLocked);
threads[i] = t;
t.Start();
}
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < threads.Length; i++)
{
threads[i].Join();
}
sw.Stop();
Console.WriteLine($"Interlocked finished in : {sw.ElapsedMilliseconds}, value = {_testB.GetValue()}");
}
private static void TestLocked(int numofthreads)
{
Thread[] threads = new Thread[numofthreads];
for (int i = 0; i < numofthreads; i++)
{
Thread t = new Thread(StartTestLocked);
threads[i] = t;
t.Start();
}
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < threads.Length; i++)
{
threads[i].Join();
}
sw.Stop();
Console.WriteLine($"Locked finished in : {sw.ElapsedMilliseconds}, value = {_testB.GetValue()}");
}
private static void StartTestInterLocked()
{
int counter = 10000000;
for (int i = 0; i < counter; i++)
{
_testB.IncrInterLocked();
}
}
private static void StartTestLocked()
{
int counter = 10000000;
for (int i = 0; i < counter; i++)
{
_testB.IncrLocked();
}
}
程序的輸出是...
Interlocked finished in : 76909 ms, value = 1000000000
Locked finished in : 44215 ms, value = 2000000000
你只測試這裏有很多併發訪問的情況。對於更公平的測試,您還應該測試在沒有併發訪問或正常數量時哪個更快。 – hvd
我認爲你的測量是有缺陷的。在啓動秒錶之前,啓動所有線程。在測量開始之前,許多線程即使不是大部分線程也將完成。 –