Re: What does volatile guarantee?
On 2/14/2010 4:30 PM, Andreas Leitgeb wrote:
Lew <noone@lewscanon.com> quoted:
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;
I'm not whining (nor suggesting) for += nor ++ being atomic,
but that particular argument does not extend to the "++"
operator.
So, what to say to those whining^H^H^H^H^H^H^Hsuggesting
making just "++" atomic?
Just curious.
Could be (or have been) done, I guess. Nowadays most
machines have compare-and-swap or something of the kind, and
these can be repeated in a loop until successful:
loop: load r0,x
load r1,r0
inc r1
cas r0,r1,x // if x==r0, set x=r1 and r1==x
cmp r0,r1 // did the swap happen?
jneq loop // failed: retry
Such instructions tend to be fairly expensive, though, since
they need to do things like flush a CPU's store buffers and
maybe bypass caches to go all the way to (s-l-o-w) RAM. The
expense isn't fatal in and of itself (`synchronized' needs to
do similar things) -- but from a language perspective it means
you can no longer say "++ is shorthand for +=1" unless you also
promise atomicity for +=, and then comes the slippery slope.
Atomic x++ when x is Double.NaN could be *really* fun ...
--
Eric Sosman
esosman@ieee-dot-org.invalid