例子:
Thread a: Interlocked.Increment(ref x);
Thread b: int currentValue = x;
假设线程 b 在线程 a 之后执行,线程 b 中的“currentValue”是否保证是递增的值?或者,线程 b 是否需要执行 Thread.VolatileRead(ref x)?
最佳答案
从技术上讲,这取决于运行 .NET 的 CPU,但对于任何常见的 CPU,答案是肯定的,Interlocked.Increment 可以保证缓存一致性。它acts as a memory barrier按照 MESI 的要求。
a CPU can have in its cache a line which is invalid, but where it doesn't yet know that line is invalid - the invalidation queue contains the invalidation which hasn't yet been acted upon. (The invalidation queue is on the other "side" of the cache; the CPU can't scan it, as it can the store buffer). As a result, memory barriers are required.
http://en.wikipedia.org/wiki/MESI_protocol (x86)
MOESI(用于 AMD64 芯片)非常相似:
http://en.wikipedia.org/wiki/MOESI_protocol (AMD64)
关于.net - Interlocked.Xxx 方法是否保证在所有数据缓存中更新值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13850432/