Atomicity of 32bit read on multicore CPU

后端 未结 4 877
温柔的废话
温柔的废话 2021-01-18 09:46

(Note: I\'ve added tags to this question based on where I feel will people will be who are likely to be able to help, so please don\'t shout:))

In my VS 2017 64bit p

4条回答
  •  时光取名叫无心
    2021-01-18 10:11

    In C++11, an unsynchronized access to a non-atomic object (such as m_lClosed) is undefined behavior.

    The standard provides all the facilities you need to write this correctly; you do not need non-portable functions such as InterlockedCompareExchange. Instead, simply define your variable as atomic:

    std::atomic m_lClosed{false};
    
    // Writer thread...
    bool expected = false;
    m_lClosed.compare_exhange_strong(expected, true);
    
    // Reader...
    if (m_lClosed.load()) { /* ... */ }
    

    This is more than sufficient (it forces sequential consistency, which might be expensive). In some cases it might be possible to generate slightly faster code by relaxing the memory order on the atomic operations, but I would not worry about that.

提交回复
热议问题