When to use 'volatile' or 'Thread.MemoryBarrier()' in threadsafe locking code? (C#)

前端 未结 4 475
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 04:25

When should I use volatile/Thread.MemoryBarrier() for thread safety?

4条回答
  •  既然无缘
    2020-12-09 04:59

    Basically if you're using any other kind of synchronization to make your code threadsafe then you don't need to.

    Most of the lock mechanisms (including lock) automatically imply a memory barrier so that multiple processor can get the correct information.

    Volatile and MemoryBarrier are mostly used in lock free scenarios where you're trying to avoid the performance penalty of locking.

    Edit: You should read this article by Joe Duffy about the CLR 2.0 memory model, it clarifies a lot of things (if you're really interested you should read ALL the article from Joe Duffie who is by large the most expert person in parallelism in .NET)

提交回复
热议问题