views:

298

answers:

3

Reading and writing of a single variable is atomic (language guarantee!), unless the variable is of type long or double.

I was reading a course slides and i found that written. The class was about concurrency.

Can anyone explain me why writing a long or a double is not an atomic operation? It really got me by surprise.

+6  A: 

It's not atomic because it's a multiple-step operation at the machine code level. That is, longs and doubles are longer than the processor's word length.

Don Branson
Right. And on a 64 bit machine with a 64 bit long, writing long probably *will* be atomic, unless you're talking about a JVM or something.
Paul Tomblin
in a 64 machine a long will have 128 bit as the int already as 64
fmsf
Depends on the langauge I guess. I'm pretty sure that Java's primitive types are guaranteed to be a particular length across all machines.
Outlaw Programmer
The .NET framework has its "primitives" set to specfic bit lengths as well, rather that a number of bytes. int is a synonym for Int32, which is always going to be 32 bits...
Beska
Some languages (like C and C++) have integral types defined to be at least so big; some, like Java, have them fully defined.
David Thornley
This is not true of all languages. Of course it's often a sensible assumption to expect machine-word sized data, and nothing else, to be atomic, but it's a property of the language. Unless you specify a language, it's impossible to say what is/isn't atomic.
jalf
It also depends on the cpu he's on. I understand that. But for this guy, it's probably safe to say that he's not running an exotic language on exotic hardware. And since he stated from the beginning that they're not atomic, I'm explaining the most likely reason.
Don Branson
+3  A: 

This question really needs to be tied to a language. C89, for instance, didn't say anything about atomic operations because it didn't say anything about threads.

Darron
Not to mention that C and C++ make pretty loose promises about the size of various types (specifically a long might or might not be the size of a machine word).
Michael Burr
A: 

Just to clarify the situation for Java, doubles and longs are not read or written to atomically unless they're declared volatile

JLS - Nonatomic Treatment of double and long

daveb