user997112
user997112

Reputation: 30605

Implement a C++ lock using atomic instructions?

I saw a question on a website the other day and at first I thought the answer was trivial, but then I thought it wasnt.

How do you implement a lock using atomic instructions? Compare and swap is the standard way of atomically checking the value of something, but it is intended to be for lock-free designs, hence my bewilderment....

Upvotes: 2

Views: 6582

Answers (1)

Collin Dauphinee
Collin Dauphinee

Reputation: 13973

You're probably referring to a spin lock when you say 'a lock using atomic instructions.'

A spin lock is just a single atomic integer (or boolean) with two values: LOCKED and UNLOCKED. The locking function does an atomic compare and swap in a while loop, until it successfully modifies the value from UNLOCKED to LOCKED, at which point this thread owns the lock. The unlock function just resets the value of the atomic back to UNLOCKED.

class spin_lock
{
    constexpr int UNLOCKED = 0;
    constexpr int LOCKED = 1;

    std::atomic<int> m_value = 0;

public:
    void lock()
    {
        while (true)
        {
            int expected = UNLOCKED;
            if (m_value.compare_exchange_strong(expected, LOCKED))
                break;
        }
    }

    void unlock()
    {
        m_value.store(UNLOCKED);
    }
};

It's also incorrect to say that atomic compare and swap instructions are intended for lock-free designs; they're very important to all forms of synchronization.

Upvotes: 8

Related Questions