Interlocked and Memory Barriers

前端 未结 7 2008
情书的邮戳
情书的邮戳 2021-02-02 18:04

I have a question about the following code sample (m_value isn\'t volatile, and every thread runs on a separate processor)

void Foo() // executed by thr         


        
7条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-02 18:51

    Interlocked.Exchange() should guarantee that the value is flushed to all CPUs properly - it provides its own memory barrier.

    I'm surprised that the compiler is complaing about passing a volatile into Interlocked.Exchange() - the fact that you're using Interlocked.Exchange() should almost mandate a volatile variable.

    The problem you might see is that if the compiler does some heavy optimization of Bar() and realizes that nothing changes the value of m_value it can optimize away your check. That's what the volatile keyword would do - it would hint to the compiler that that variable may be changed outside of the optimizer's view.

提交回复
热议问题