read/write volatile
read/write volatile
Posted Jan 10, 2026 20:44 UTC (Sat) by NYKevin (subscriber, #129325)In reply to: read/write volatile by plugwash
Parent article: READ_ONCE(), WRITE_ONCE(), but not for Rust
That is true but misleading. Your parenthetical negates all of the guarantees that are actually expensive to implement, at least on x86.
Noting for the record: A fence must be on the same thread as the relaxed atomic in order to restrict it, and there are several other requirements as well. I refer the curious reader to https://en.cppreference.com/w/cpp/atomic/atomic_thread_fe... and related documentation for more information.
> My understanding is that this effectively means that if you implement read-modify-write operations by using a global lock, you must also implement plain write operations using that same global lock.
If you take a global lock, then there are two different memory locations in play (lock and payload), so your parenthetical above already tells us that the lock is ineffective (at protecting against against un-fenced relaxed atomics on either the lock or the payload).
Or perhaps I have misunderstood what you mean by "implement read-modify-write operations by using a global lock." I would normally understand a "read-modify-write operation" to be a hardware instruction (or sequence of instructions), which is not our problem to "implement" in the first place. If you mean "emulate," then the problem we run into is that emulators do not emulate the C abstract machine. They emulate some real hardware like x86, or virtual hardware like the JVM. Those platforms have their own, more specific memory models than the C abstract machine, and the compiler backend must necessarily take advantage of those memory models to emit correct assembly/machine code. So our emulator is not permitted to stop at just taking locks for relaxed atomics - it doesn't necessarily know which stores or loads originated as relaxed atomics in the first place, and therefore may have to take locks for all loads and stores whatsoever. Of course, it would be preferable to implement these operations lock-free if it is possible to do so.
