一、测试代码
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace 测试interlock
{
class Program
{
private static object lockObj = new object();
private static int Count = 0;
static void Main(string[] args)
{
int threadCount = 10;
for (int k = 0; k < 10; k++)
{
Count = 0;
var watch = new Stopwatch();
watch.Start();
var tasks = new List<Task>();
for (int i = 0; i < threadCount; i++)
{
var task = Task.Factory.StartNew(
() =>
{
for (int j = 0; j < 10000000; j++)
{
OnlyLockTest();
}
});
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray());
watch.Stop();
Console.WriteLine(k + 1 + " 线程数:" + threadCount + ", Lock耗时:" + watch.ElapsedTicks + ",计算结果: " + Count);
Count = 0;
watch = new Stopwatch();
watch.Start();
var tasks1 = new List<Task>();
for (int i = 0; i < threadCount; i++)
{
var task = Task.Factory.StartNew(
() =>
{
for (int j = 0; j < 10000000; j++)
{
InterlockedTest();
}
});
tasks1.Add(task);
}
Task.WaitAll(tasks1.ToArray());
watch.Stop();
Console.WriteLine(k + 1 + " 线程数:" + threadCount + ", Interlocked耗时:" + watch.ElapsedTicks + ",计算结果: " + Count);
}
Console.ReadKey();
}
private static void OnlyLockTest()
{
lock (lockObj)
{
Count++;
}
}
private static void InterlockedTest()
{
Interlocked.Increment(ref Count);
}
}
}
二、测试结果
测试机器:4核cpu,8G内存,win10
设置线程数为2,执行10000000次,跑10遍
三、结论
在cpu可用范围内,Interlocked性能还是更优越一点的