Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Archives
Today
Total
관리 메뉴

For me

[Server] Lock - 3 (SpinLock) 본문

Server/Study

[Server] Lock - 3 (SpinLock)

GiveZero 2023. 4. 26. 15:48

SpinLock

1) bool 형식을 사용하여 구현

당연한 결과지만..

class SpinLock
    {
        volatile bool _locked = false;
        
        public void Acquire()
        {
             while (_locked)
             {
                 
             }
            
             _locked = true;
        }

        public void Release()
        {
            _locked = false;
        }
    }

결과 작동 X

 

2) Interlocked.Exchange() 을 이용하여 구현

 

class SpinLock
    {
        volatile int _locked = 0;
        
        public void Acquire()
        {
            while (true)
            {                 
                 int original = Interlocked.Exchange(ref _locked, 1); // original 에서는 하나의 스레드에서 사용하는 값 
                 if (original == 0)
                 {
                      break;
                 }                 
            }
        }

        public void Release()
        {
            _locked = 0;
        }
    }

결과 작동 O

 

3) InterLocked.CompareExchange()사용하여 구현

class SpinLock
    {
        volatile int _locked = 0;
        // volatile bool _locked = false;
        
        public void Acquire()
        {
            while (true)
            {              
                //CAS (Compare-And-Swap)                
                 int expected = 0;
                 int desired = 1;
                 
		// if(_lock == expected ) _lock = desired; 와 같음
                 if (Interlocked.CompareExchange(ref _locked, desired, expected) == expected) 
                 {
                     break;
                 }       
            }
        }

        public void Release()
        {
            _locked = 0;
        }
    }

결과 작동 O

'Server > Study' 카테고리의 다른 글

[Server] AutoResetEvent  (0) 2023.04.26
[Server] Context Switching  (0) 2023.04.26
[Server] Lock - 2  (0) 2023.04.26
[Server] Lock - 1  (0) 2023.04.26
[Server] Interlocked  (1) 2023.04.26