volatile variables in D....

David B. Held dheld at codelogicconsulting.com
Wed Apr 11 23:36:52 PDT 2007


Forest Ray wrote:
> 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'.

In fact, C++'s 'volatile' isn't guaranteed to do the right thing because 
C++ doesn't define a memory model which would be necessary to define 
what The Right Thing even is.  Java made the same mistake at first, but 
later fixed the standard to properly define 'volatile'.  While setting 
up memory barriers etc. to make volatile work properly might seem like a 
quick and easy solution, I think we need to think carefully about what 
multithreading primitives really give the most benefit.

In this case, you basically want volatile to give you a cheap form of 
atomic increment.  However, I would suggest that if you really need the 
accuracy of atomic increment, then you should consider a primitive like 
CAS instead:

int count = 0;

asm
{
     MOV EBX, &count;
     MOV EAX, [EBX];
Retry:
     MOV EDX, EAX;
     INC EDX;
     CMPXCHG [EBX], EDX;
     JNZ Retry;
}

My x86 asm is pretty rusty, so this might be completely bogus code, but 
it should give you an idea of what I mean.

Dave



More information about the Digitalmars-d mailing list