.net - Interlocked.Xxx 方法是否保证在所有数据缓存中更新值?

标签 .net multithreading

例子:

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/

相关文章:

java - 如何使 2 个服务器线程与 2 个客户端线程通信?

c# - 从代码中获取来自 google oauth 的访问 token

c# - 这个双重检查锁是否需要 volatile 关键字才能工作?

ios - viewDidLoad多线程问题

c# - 是否必须提供与C#中的多线程相关的事件的场景?

java - 无法打破经典的延迟初始化单例

java - 关于线程和进程的一个问题

.net - 设置默认样式键的方法之间的差异

c# - App.xaml 尝试在 Windows Phone 8 项目中使用 MVVM Light 时出错

c# - IsSerializable 为标记为 Serializable 的对象返回 "false"