Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does acquiring a spinlock require compare-and-swap or is swap enough?

Suppose we have a spinlock implementation:

struct Lock {
    locked : Atomic(bool),
}

Then an unlock function could be:

fun unlock(lock : &Lock) {
    atomic_store(&lock.locked, false, release);
}

But what about lock? Commonly, it uses a compare-and-swap like this:

fun lock(lock : &Lock) {
    while atomic_compare_and_swap(&lock.locked, false, true, acquire) {}
}

But wouldn't a swap be enough for this? Something like this:

fun lock(lock : &Lock) {
    while atomic_swap(&lock.locked, true, acquire) {}
}

Is there any problem with this?

like image 560
bzim Avatar asked Oct 12 '25 05:10

bzim


1 Answers

A compare-and-swap isn't really necessary. Atomically setting a flag true if it is false is logically equivalent to unconditionally setting it true.

An unconditional swap might be slightly faster since it does not have to compare anything, although the real cost of an atomic read-modify-write operation is in obtaining and locking the cache line.

Here is an example of a C++ spinlock that uses exchange()

#include <atomic>

class mutex {
    std::atomic<bool> flag{false};

public:
    void lock()
    {
        while (flag.exchange(true, std::memory_order_acquire));
    }

    void unlock()
    {
        flag.store(false, std::memory_order_release);
    }
};
like image 170
LWimsey Avatar answered Oct 15 '25 03:10

LWimsey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!