For me
[Server] Lock - 3 (SpinLock) 본문
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 |