threads are the bug

Henry Cejtin henry@sourcelight.com
Thu, 5 Jul 2001 20:39:32 -0500


The  `grinding  for  a while' just makes it more likely.  The point is that C
compilers can assume single threadedness (and hence no interrupts)  for  non-
volatile variables.  The rule for volatile is (and this is a pretty low level
notion of semantics, that's for sure) that  every  reference  to  a  volatile
object must actually cause it to be fetched again.  For non-volatile objects,
that isn't true, and the compiler can lift multiple references into one.   As
a trivial example, if you do

    int     x,
            y;

    y = x + x + x;

then  the  compiler can legally fetch x, multiply it by 3 and use that for y.
If, on the other hand, you say

    volatile int    x,
    int             y;

    y = x + x + x;

then the compiler must fetch x 3 times and add them together.

The name `volatile' is truly horrible.  The really correct name  is  `shared'
since  you  are sharing it with something else.  That something else might be
another thread, or a signal handler, or it might be that the  location  x  is
bound to is really a device register (so you are sharing it with the hardware
of the device).