【发布时间】:2016-05-10 16:05:38
【问题描述】:
出于好奇,我编写了一个程序来测试 InterLocked 与 .Net 中的锁定的性能。 事实证明,InterLocked 版本比 Locked 版本慢得多,如果我在这里遗漏了一些细节,请有人指出。 根据我的理解,Interlocked 的性能应该比 lock 好得多。
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
【问题讨论】:
-
您只是在测试这里有大量并发访问的情况。为了更公平的测试,您还应该在没有并发访问或正常数量的情况下测试哪个更快。
-
我认为你的测量有缺陷。在启动 StopWatch 之前启动所有线程。许多(如果不是大多数)线程将在测量开始之前完成。
标签: c# multithreading