C++ memory ordering

Viewed 588

In some tutorial i saw such spin lock implementation

class spin_lock 
{
    atomic<unsigned int> m_spin ;

public:
    spin_lock(): m_spin(0) {}
    ~spin_lock() { assert( m_spin.load(memory_order_relaxed) == 0);}

    void lock()
    {
        unsigned int nCur;
        do { nCur = 0; }
        while ( !m_spin.compare_exchange_weak( nCur, 1, memory_order_acquire ));
    }
    void unlock()
    {
        m_spin.store( 0, memory_order_release );
    }
};

Do we really need memory_order_acquire / memory_order_release tags for compare_exchange_weak and store operations respectively? Or memory_order_relaxed is sufficient in this case as there is no Synchronizes-With relation?

Update: Thank you for the explanations! I was considering spin_lock without context in which it is used.

2 Answers
Related