Need help with communication between multiple threads

Sean Kelly sean at
Tue Feb 20 12:00:35 PST 2007

kris wrote:
> 4) use a small discrete unit for the value. If value is just a byte, the 
> underlying hardware will usually treat it as an indivisible unit, giving 
> you the desired result (similar to #3). However, there are memory 
> barriers involved also, which D respects via the "volatile" keyword. 
> Beyond that, there may be issues with cache-reconciliation on a 
> multi-core device, so this approach is generally not recommended.

The "volatile" keyword is somewhat tricky, as it's effectively a memory 
barrier for compiler optimizations only.  It will prevent the compiler 
from moving loads/stores across the volatile region during optimization, 
but it does not affect the ASM code in any way.  I think it will also 
affect whether register caching of loads occurs, etc, which is 
occasionally necessary if you're performing a busy wait on a shared 
variable.  ie, under normal circumstances:

     while( i == 0 )
         // do nothing

it's clear to the compiler that the value of 'i' will not change during 
the loop, so the code could theoretically be transformed into:

     if( i == 0 )
         while( true )
             // do nothing

which is an equivalent sequence of operations.  In C++, this is called 
the "as if" rule: the compiler can do whatever the heck it wants so long 
as the behavior meets expectations /within the context of the virtual 
machine described for the language/.  For C++, this virtual machine is 
single-threaded so the above transformation is legal.  I believe the 
same is currently true of D, though D provides "volatile" to tell the 
compiler "I don't care what fancy stuff you think you can do to this 
code to make it faster.  Don't do it.  I know more than you do about 
what's going on here."

That said, progress is being made towards defining a multithreaded 
virtual machine for C++, and once it is settled I suspect the D model 
will follow the C++ model in spirit, if perhaps not exactly.

By the way, for any who are interested, Doug Lea described a memory 
model last month that I think has tremendous promise, regardless of 
whether it's chosen for C++.  He describes it here:


More information about the Digitalmars-d-learn mailing list