C# 内存模型是否保证持有锁的线程一定能看到执行的所有更新,而其他线程以前持有相同的锁?
我一直在阅读 c# 规范,但似乎无法找到这方面的细节。
请您参考如下方法:
寻求直观的解释:如果不提供该保证,则无法实现锁定。
寻求正式解释:CLI 规范 (Ecma 335) 第 I.12.6.5 章涵盖了这一点:
Acquiring a lock (System.Threading.Monitor.Enter or entering a synchronized method) shall implicitly perform a volatile read operation, and releasing a lock (System.Threading.Monitor.Exit or leaving a synchronized method) shall implicitly perform a volatile write operation.
A volatile read has “acquire semantics” meaning that the read is guaranteed to occur prior to any references to memory that occur after the read instruction in the CIL instruction sequence. A volatile write has “release semantics” meaning that the write is guaranteed to happen after any memory references prior to the write instruction in the CIL instruction sequence.
