短时间锁定的情况下,自旋锁(spinlock)更快。(因为自旋锁本质上不会让线程休眠,而是一直循环尝试对资源访问,直到可用。所以自旋锁线程被阻塞时,不进行线程上下文切换,而是空转等待。对于多核CPU而言,减少了切换线程上下文的开销,从而提高了性能。)
以下是简单实例(并行执行10000次,每次想list中添加一项。执行完后准确的结果应该是10000):
foo1:使用系统的自旋锁。
foo4:不使用锁。结果必然是不正确的。
foo5:通过Interlocked实现自旋锁。
public class SpinLockDemo
{
int i = ;
List<int> li = new List<int>();
SpinLock sl = new SpinLock();
int signal = ; public void Execute()
{
foo1();
//li.ForEach((t) => { Console.WriteLine(t); });
Console.WriteLine("Li Count - Spinlock: "+li.Count);
li.Clear();
foo4();
Console.WriteLine("Li Count - Nolock: " + li.Count);
li.Clear();
foo5();
Console.WriteLine("Li Count - Customized Spinlock: " + li.Count); } public void foo1()
{
Parallel.For(, , r =>
{
bool gotLock = false; //释放成功
try
{
sl.Enter(ref gotLock); //进入锁
//Thread.Sleep(100);
if (i == )
{
i = ;
li.Add(r);
i = ;
}
}
finally
{
if (gotLock) sl.Exit(); //释放
} });
} public void foo4()
{
Parallel.For(, , r =>
{
if (i == )
{
i = ;
li.Add(r);
i = ;
}
});
} public void foo5()
{
Parallel.For(, , r =>
{
while (Interlocked.Exchange(ref signal, ) != )//加自旋锁
{}
li.Add(r);
Interlocked.Exchange(ref signal, ); //释放锁
}); } public void foo6()
{
//Console.WriteLine(i);
//Task.Run(new Action(foo2)).ContinueWith(new Action<Task>(t =>
//{
// Console.WriteLine("foo2 completed: " + i);
//}));
//Console.WriteLine(i);
//Task.Run(new Action(foo2)).ContinueWith(new Action<Task>(t =>
//{
// Console.WriteLine("foo3 completed: " + i);
//}));
//Console.WriteLine(i);
}
public void foo2()
{
bool lck = false;
sl.Enter(ref lck);
Thread.Sleep();
++i;
if (lck) sl.Exit();
} public void foo3()
{
bool lck = false;
sl.Enter(ref lck);
++i;
if (lck) sl.Exit();
}
}
结果如下: