volatile variables in D....

Forest Ray disto at flying-guillotine.com
Thu Apr 12 14:16:43 PDT 2007


Here is a more concrete example which should not get confused with atomic access.  I am an embedded/OS programmer.  I have to use memory mapped devices all of the time.  In C/C++ I must declare references to these address as volatile pointers otherwise the compiler may NOT actually access that address.  An optomizing compiler will cache the value from the first reference and not read/write the other accesses.  For example, I have a serial port device mapped into my address space:

volatile unsigned char* serial_base = 0x00000020;

then I need to read 3 character from the serial port:

x = *serial_base;
y = *serial_base;
z = *serial_base;

If serial_base is NOT volatile and I have a modern optimizing compiler x, y, and z will all have the same value as serial_base was only accessed once.  The first memory load from serial_base is stored in x then copied to y and z.  volatile tells the compiler not to optimize the serial_base variable and always read from/write to it.

If D is to be considered in the embedded enviroment this has to be addressed.  D's volatile statement is error prone, I would have to declare each STATEMENT that used serial_base as volatile, that is horrible.



Davidl Wrote:

> worth consideration!!
> And the volatile statement we have now is completely not usable compare to
> C++'s volatile prefix vars
> 
> > What is the correct way to impliment a volatile variable ala C++ in D?   
> > For example an ISR which triggers
> > every 1 ms does some work and increments a heartbeat variable.  How does  
> > one define this?  In C++ you
> > would define it as "volatile unsigned int timer_1ms;" and all referance  
> > would aways read from/write to the
> > memory location.  In D do you have to use the volatile key word on every  
> > statement that access this
> > variable?  That would be rather klunky and error prone, not to mention  
> > gdc does not always do the correct
> > thing.  Now that D is getting proper 'const', maybe it should get proper  
> > 'volatile'.
> >
> > Mark
> 




More information about the Digitalmars-d mailing list