Does Interlocked.CompareExchange use a memory barrier?

前端 未结 6 1026
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-27 18:55

I\'m reading Joe Duffy\'s post about Volatile reads and writes, and timeliness, and i\'m trying to understand something about the last code sample in the post:

<         


        
6条回答
  •  星月不相逢
    2020-11-27 19:35

    The interlocked functions are guaranteed to stall the bus and the cpu while it resolves the operands. The immediate consequence is that no thread switch, on your cpu or another one, will interrupt the interlocked function in the middle of its execution.

    Since you're passing a reference to the c# function, the underlying assembler code will work with the address of the actual integer, so the variable access won't be optimized away. It will work exactly as expected.

    edit: Here's a link that explains the behaviour of the asm instruction better: http://faydoc.tripod.com/cpu/cmpxchg.htm
    As you can see, the bus is stalled by forcing a write cycle, so any other "threads" (read: other cpu cores) that would try to use the bus at the same time would be put in a waiting queue.

提交回复
热议问题