Re: What does volatile guarantee?
On 2/14/2010 10:32 PM, Andreas Leitgeb wrote:
Lew <noone@lewscanon.com> wrote:
Eric Sosman wrote in this thread on 2/12:
Before anybody whines^H^H^H^H^H^Hsuggests that making +=
atomic would be easy, let him ponder
volatile int a,b,c,...,z;
a += b += c+= ... += z;
On re-thought, even Eric's argument seems not too strong anymore:
First, z is read,
Then y is atomically increased by the previously read value.
Then x ...
...
While e.g. "n" is increased, some other thread could modify "a" and "z".
Obviously, that is irrelevant to the current thread, which no longer
cares for "z"'s value, and not yet cared for "a"'s old value.
...
Finally the resulting value of "b" would be added to the new value of "a".
No ambiguities involved.
It breaks Java's "left to right evaluation" rule, though.
Whether that's important is for you as a language designer to
decide.
So it's all just about whether "++","--","+=" and "-=" would be made
shorthands for what is already possible by the Atomic* classes.
The real reason boils down to that those atomic operations are still
slightly slower than the non-atomic ones, while the cases not caring
about atomicity by far outnumber the others. That's why I added
those "(not me!)"s.
My impression (I'm by no means a hardware expert) is that the
time penalty is considerably worse than "slight." It'll depend a
lot on the nature of the hardware, though.
--
Eric Sosman
esosman@ieee-dot-org.invalid