본문 바로가기
둥지/Server

스핀락 구현

by 까닭 2023. 2. 13.
#include <iostream>
#include <thread>
#include <atomic>
#include <mutex>

__int32 sum = 0;
std::mutex m = {};

class SpinLock
{
public :
    void lock() 
    {
        bool expected = false; 
        bool desired = true;

	//접근할 수 있을 때까지 대기
        while (false == _locked.compare_exchange_strong(expected, desired))
        {
            expected = false;
            std::this_thread::yield();
        }
    }

    void unlock()
    {
        _locked.store(false);
    }

private:
    std::atomic<bool> _locked = false; 
};
 
void Add()
{
    for (size_t i = 0; i < 100'000; ++i)
    {
        std::lock_guard<SpinLock> guard(spinLock);
        ++sum;
    }
}

void Sub()
{
    for (size_t i = 0; i < 100'000; ++i)
    {
        std::lock_guard<SpinLock> guard(spinLock);
        --sum;
    }
}

SpinLock spinLock;

int main()
{
    std::thread t1(Add);
    std::thread t2(Sub);

    t1.join();
    t2.join();

    std::cout << sum << std::endl;
}