spinwaitlock.cs

来自「破解的飞信源代码」· CS 代码 · 共 53 行

CS
53
字号
namespace NCindy.Util
{
    using System;
    using System.Runtime.InteropServices;
    using System.Threading;

    [StructLayout(LayoutKind.Sequential)]
    public struct SpinWaitLock
    {
        private const int LockIsFree = 0;
        private const int LockIsOwned = 1;
        private static readonly bool IsSingleCpuMachine;
        private int lockState;
        public void Enter()
        {
            Thread.BeginCriticalRegion();
            while (Interlocked.Exchange(ref this.lockState, 1) != 0)
            {
                while (Thread.VolatileRead(ref this.lockState) == 1)
                {
                    StallThread();
                }
            }
        }

        public void Exit()
        {
            Interlocked.Exchange(ref this.lockState, 0);
            Thread.EndCriticalRegion();
        }

        private static void StallThread()
        {
            if (IsSingleCpuMachine)
            {
                SwitchToThread();
            }
            else
            {
                Thread.SpinWait(1);
            }
        }

        [DllImport("kernel32", ExactSpelling=true)]
        private static extern void SwitchToThread();
        static SpinWaitLock()
        {
            IsSingleCpuMachine = Environment.get_ProcessorCount() == 1;
        }
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?