should a double or long variable be declared volatile to achieve read\write atomicy in a 64bit OS and a 64bit cpu?is the same true for a 32bit os and 32bit processor?
Asked
Active
Viewed 170 times
2 Answers
4
There are two answers to this, and neither are what you hope to hear:
- No,
volatile
does not guarantee atomicity, so if you need atomicity,volatile
won't help you. - With or without
volatile
, the atomicity is really implementation-defined. On nearly all CPUs, native word-sized variables are read and written atomically (at least if they're properly aligned, which will normally be the case). On x86, smaller ones are atomically accessed too. So yes, on x86, a 32-bit variable will be read/written atomically, and on x86, a 64-bit variable will also be read/written atomically. But again, it depends on the CPU (and the compiler).

jalf
- 243,077
- 51
- 345
- 550
-
agree on "volatile does not guarantee atomicity", but the second statement heavily depends on the number of cores/processors. With multiple CPUs, even a word-sized memory access is not atomic (or at least not guaranteed), because another CPU might access the variable at the same time. In assembler, you can use the `LOCK` prefix to access atomically among CPUs. In C or higher languages, you should always use some kind of synchronization (e.g. mutex). – kuba Apr 15 '12 at 11:27
-
@JohnSmith: no, no matter how many cores or CPUs you have, (well-aligned) word-sized accesses are atomic on x86. The LOCK prefix gives a more powerful guarantee (it locks the memory bus, effectively serializing access to memory), but even without it, you're still guaranteed that reads/writes are atomic. – jalf Apr 15 '12 at 11:44
-
Just to back up my claim, check [this answer](http://stackoverflow.com/a/5178914/33213) :) – jalf Apr 15 '12 at 11:58
0
volatile
will not help here. If an operation is to be non-atomic it needs a full lock to guard against concurrent access trouble.
Having said this, tearing of a long
variable on 32-bit systems is a well know issue and you can find examples to demonstrate this (see below link).
double
variables can also cause tearing but it's a bit harder to replicate since floating point unit registers are 80 bits on x86 systems. Have a look here: Simulate tearing a double in C# for a great answer by Hans Passant.