版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011915028/article/details/53011811
一下解释摘自msdn msdn链接
通常,在保持一个旋锁时,应避免任何这些操作:
-
阻塞,
-
调用本身可能阻塞的任何内容,
-
一次保持多个自旋锁,
-
进行动态调度的调用(接口和虚方法)
-
在某一方不拥有的任何代码中进行动态调度的调用,或
-
分配内存。
SpinLock 实例,则应该通过引用而不是通过值传递。
SpinLock 实例存储在只读字段中。
实例代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace spinLock
{
class Program
{
//得到当前线程的handler
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentThread();
//创建自旋锁
private static SpinLock spin = new SpinLock();
public static void doWork1()
{
bool lockTaken = false;
try
{
//申请获取锁
spin.Enter(ref lockTaken);
//下面为临界区
for(int i=0;i<10;++i)
{
Console.WriteLine(2);
}
}
finally
{
//工作完毕,或者发生异常时,检测一下当前线程是否占有锁,如果咱有了锁释放它
//以避免出现死锁的情况
if (lockTaken)
spin.Exit();
}
}
public static void doWork2()
{
bool lockTaken = false;
try
{
spin.Enter(ref lockTaken);
for (int i = 0; i < 10; ++i)
{
Console.WriteLine(1);
}
}
finally
{
if (lockTaken)
spin.Exit();
}
}
static void Main(string[] args)
{
Thread[] t = new Thread[2];
t[0] = new Thread(new ThreadStart(doWork1));
t[1] = new Thread(new ThreadStart(doWork2));
t[0].Start();
t[1].Start();
t[0].Join();
t[1].Join();
Console.ReadKey();
}
}
}