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

亡梦爱人 提交于 2019-12-24 07:37:08

问题


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?


回答1:


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);
    }
};


来源:https://stackoverflow.com/questions/53280739/does-acquiring-a-spinlock-require-compare-and-swap-or-is-swap-enough

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!