Atomicity of 32bit read on multicore CPU

后端 未结 4 912
温柔的废话
温柔的废话 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:07

    As I posted here, this question was never about protecting a critical section of code, it was purely about avoiding torn read/writes. user3386109 posted a comment here which I ended up using, but declined posting it as an answer here. Thus I am providing the solution I ended up using for completeness of this question; maybe it will help someone in the future.

    The following shows the atomic setting and testing of m_lClosed:

    long m_lClosed = 0;
    

    Thread 1

    // Set flag to closed
    if (InterlockedCompareExchange(&m_lClosed, 1, 0) == 0)
        cout << "Closed OK!\n";
    

    Thread 2

    This code replaces if (!m_lClosed)

    if (InterlockedCompareExchange(&m_lClosed, 0, 0) == 0)
        cout << "Not closed!";
    

提交回复
热议问题