Are volatile variables useful? If yes then when?

前端 未结 3 1028
长情又很酷
长情又很酷 2021-02-19 08:36

Answering this question made me think about something is still not clear for me. Let\'s first assume we read all from this post and this post.

[begin edit] Mayb

3条回答
  •  梦谈多话
    2021-02-19 09:12

    How lock will prevent cache problem? Is it implicit a memory barrier in a critical section?

    Yes, lock also acts as a full fence (it has both acquire and release semantics). This page on the Windows dev center explains how this works:

    Processors can support instructions for memory barriers with acquire, release, and fence semantics. These semantics describe the order in which results of an operation become available. With acquire semantics, the results of the operation are available before the results of any operation that appears after it in code. With release semantics, the results of the operation are available after the results of any operation that appears before it in code. Fence semantics combine acquire and release semantics. The results of an operation with fence semantics are available before those of any operation that appears after it in code and after those of any operation that appears before it.


    Volatile variables can't be local (I read something from Eric Lippert about this but I can't find that post now and I don't remember his answer). This makes me think they're not implemented with an Interlocked.CompareExchange() and friends, in what they're different?

    What volatile modifier will do for example in this code?

    They are different in that they do not prevent race conditions involving other threads operating on the same memory. A read/modify/store involving a volatile field will not be atomic as a whole even though each of the three steps will be (C# has chosen to guarantee atomicity for volatile reads and writes).

    The volatile on the sample code won't do much. It will make certain that when the read/modify/store sequence for incrementing _volatileField begins the read will actually go to memory instead of being possibly satisfied from the processor cache, but it will not help at all with race conditions if there are other threads that concurrently write to the field.

提交回复
热议问题