반응형

SpinLock 사용 예시

 

static SpinLock _lock

 

Enter 에서 현재 lock 을 제대로 잡았는지에 대한 상태를 lockTaken 변수를 통해서 알 수 있게 된다

 

Enter(Boolean) 메서드 호출에서 예외가 발생하는 경우에도 안정적인 방식으로 잠금을 얻으며 잠금을 얻었는지 확인하기 위해 lockTaken을 안정적으로 검사할 수 있습니다.
Exit() 잠금을 해제합니다.
Exit(Boolean) 잠금을 해제합니다.

 

 

//      SpinLock.IsThreadOwnerTrackingEnabled
    static void SpinLockSample2()
    {
        // Instantiate a SpinLock
        SpinLock sl = new SpinLock();

        // These MRESs help to sequence the two jobs below
        ManualResetEventSlim mre1 = new ManualResetEventSlim(false);
        ManualResetEventSlim mre2 = new ManualResetEventSlim(false);
        bool lockTaken = false;

        Task taskA = Task.Factory.StartNew(() =>
        {
            try
            {
                sl.Enter(ref lockTaken);
                Console.WriteLine("Task A: entered SpinLock");
                mre1.Set(); // Signal Task B to commence with its logic

                // Wait for Task B to complete its logic
                // (Normally, you would not want to perform such a potentially
                // heavyweight operation while holding a SpinLock, but we do it
                // here to more effectively show off SpinLock properties in
                // taskB.)
                mre2.Wait();
            }
            finally
            {
                if (lockTaken) sl.Exit();
            }
        });

 

 

 

ref : https://learn.microsoft.com/ko-kr/dotnet/api/system.threading.spinlock?view=net-7.0

반응형

+ Recent posts