你的例子会很好用。
多个处理器使用MESI等一致性协议来确保数据在缓存之间保持同步。使用 MESI,每个高速缓存行都被视为已修改、独占、在 CPU 之间共享或无效。写入在处理器之间共享的高速缓存行会强制它在其他 CPU 中变为无效,从而保持高速缓存同步。
然而,这还不够。不同的处理器具有不同的内存模型,并且大多数现代处理器都支持某种程度的重新排序内存访问。在这些情况下,需要内存屏障。
例如,如果您有线程 A:
DoWork();
workDone = true;
和线程 B:
while (!workDone) {}
DoSomethingWithResults()
With both running on separate processors, there is no guarantee that the writes done within DoWork() will be visible to thread B before the write to workDone and DoSomethingWithResults() would proceed with potentially inconsistent state. Memory barriers guarantee some ordering of the reads and writes - adding a memory barrier after DoWork() in Thread A would force all reads/writes done by DoWork to complete before the write to workDone, so that Thread B would get a consistent view. Mutexes inherently provide a memory barrier, so that reads/writes cannot pass a call to lock and unlock.
In your case, one processor would signal to the others that it dirtied a cache line and force the other processors to reload from memory. Acquiring the mutex to read and write the value guarantees that the change to memory is visible to the other processor in the order expected.