/// <summary>
/// SpinWait只有在SMP或多核CPU下才具有使用意义。在单处理器下,旋转非常浪费CPU时间,没有任何意义。
/// 自旋锁特性导致其比较适用一些轻量级,极短时间的多核cpu系统上的锁保护。
/// </summary>
public struct SpinWait
{
public static readonly bool IsSingleProcessor;
private const int yieldFrequency = 4000;
private const int yieldOneFrequency = 3 * yieldFrequency;
static SpinWait()
{
IsSingleProcessor = (Environment.ProcessorCount == 1);
}
private int count;
public int Count
{
get { return count; }
}
public int Spin()
{
int oldCount = count;
// On a single-CPU machine, we ensure our counter is always
// a multiple of �s_yieldFrequency�, so we yield every time.
// Else, we just increment by one.
count += (IsSingleProcessor ? yieldFrequency : 1);
// If not a multiple of �s_yieldFrequency� spin (w/ backoff).
int countModFrequency = count % yieldFrequency;
if (countModFrequency > 0)
{
Thread.SpinWait((int)(1 + (countModFrequency * 0.05f)));
}
else
{
Thread.Sleep(count <= yieldOneFrequency ? 0 : 1);
}
return oldCount;
}
public void Yield()
{
Thread.Sleep(count < yieldOneFrequency ? 0 : 1);
}
public void Reset()
{
count = 0;
}
}