Re: What does volatile guarantee?
Eric Sosman wrote:
....
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.
In addition to the obvious costs, consider the effect on branch
prediction. The interesting case is the ++ that does not need to be
atomic, the current use of ++. In those cases, the jneq will never be
taken. However, remembering that a given jneq is not taken costs space
in the branch predictor. How frequently does ++ appear in typical Java
programs?
Deep, wide pipelines make a conditional branch very expensive if the
processor guesses wrong about whether it will be taken.
Patricia