Does Interlocked.CompareExchange use a memory barrier?

前端 未结 6 1027
佛祖请我去吃肉
佛祖请我去吃肉 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:37

    ref doesn't respect the usual volatile rules, especially in things like:

    volatile bool myField;
    ...
    RunMethod(ref myField);
    ...
    void RunMethod(ref bool isDone) {
        while(!isDone) {} // silly example
    }
    

    Here, RunMethod is not guaranteed to spot external changes to isDone even though the underlying field (myField) is volatile; RunMethod doesn't know about it, so doesn't have the right code.

    However! This should be a non-issue:

    • if you are using Interlocked, then use Interlocked for all access to the field
    • if you are using lock, then use lock for all access to the field

    Follow those rules and it should work OK.


    Re the edit; yes, that behaviour is a critical part of Interlocked. To be honest, I don't know how it is implemented (memory barrier, etc - note they are "InternalCall" methods, so I can't check ;-p) - but yes: updates from one thread will be immediately visible to all others as long as they use the Interlocked methods (hence my point above).

提交回复
热议问题