atomicLoad/Store

Sean Kelly sean at invisibleduck.org
Mon Aug 5 16:14:07 PDT 2013


On Aug 5, 2013, at 1:22 PM, zyhong <zyhong at gmail.com> wrote:

> From my understanding, any data type that is less than 32bit (bool, char, int, etc) is atomic and there is no need to use atomicLoad/Store and read/write the data to be thread safe. In std.parallelism, I saw it use atomicLoad/Store for any shared data. Could anyone clarify if it is really necessary to atomicLoad/Store to read/write data that datatype is bool, int, byte, etc?

If you are modifying something that is size_t.sizeof bytes and that data is properly aligned, it will be modified atomically on x86 assuming the compiler ever actually issues a MOV instruction.  Note that there are a lot of ifs in the previous sentence.  If you modify a bool, for example, it's possible that it could be done via a bus-width read-modify-write operation that includes the values of adjoining variables.  Or the compiler may determine that, according to the as-if rule, it doesn't have to issue the write at all, or maybe it thinks it can rearrange things so the write occurs before or after other nearby operations.

If you're super concerned about efficiency and are certain that order of operations doesn't matter, use atomicStore!msync.raw.  That will at least ensure that the write actually occurs and does so in an atomic manner.  But in general, I'd stick with the fully fenced atomic write, and really, I'd avoid atomic operations altogether and use a mutex or something similar instead.  Atomics are almost never worth the trouble that they incur in terns of added algorithm complexity.


More information about the Digitalmars-d mailing list