2

I am reading C++ Concurrency in Action by Anthony Williams, and there is a snippet of code (p. 204) for a spinlock:

class spinlock_mutex
{
    std::atomic_flag flag;
public:
    spinlock_mutex():
        flag(ATOMIC_FLAG_INIT)
    {}

    void lock()
    {
        while (flag.test_and_set(std::memory_order_acquire));
    }

    void unlock()
    {
        flag.clear(std::memory_order_release);
    }
};

What confuses me is why the author uses memory_order_acquire for the test-and-set operation, which I think is a read-modify-write operation and should be tagged with memory_order_acq_rel instead, to ensure the effect of one thread calling test_and_set can be observed by another calling test_and_set at a later point. What am I missing?

Zizheng Tai
  • 6,170
  • 28
  • 79
  • 1
    http://stackoverflow.com/questions/14791495/memory-ordering-with-atomic-flag-spin-lock?rq=1 has a useful discussion on this exact scenario. – George Newton Jan 11 '17 at 08:31

0 Answers0