synchronized vs. C volatile

Sean Kelly sean at invisibleduck.org
Mon Aug 9 15:43:42 PDT 2010


dsimcha Wrote:

> == Quote from Sean Kelly (sean at invisibleduck.org)'s article
> > As an alternative, Walter has stated before that it is invalid for the compiler
> to optimize across asm statement boundaries as well, so a similar effect can often
> be had by writing inline asm.  Similar requirements apply to shared variables as
> well, which can be modified either in-language or by importing std.concurrency or
> core.atomic to perform more complex atomic ops.  Both of these are likely to
> insert memory barriers when shared variables are accessed however.
> 
> Does this include even empty asm statements, for example:
> 
> int i;  // Volatile.
> 
> // Do stuff.
> 
> asm {}  // No code motion across this.
> i++;
> asm {} // No code motion across this.
> 
> // Do more stuff.

I wondered the same thing when writing my response.  Personally, I wouldn't consider this safe because the compiler can trivially determine that the block is empty and make it vanish.  To be safe I think you'd at least have to put a NOP in there, so I guess you could do something like:

@property void optbar() {
   asm { naked; NOP; }
}

void volatile(lazy void exp) {
    optbar;
    exp();
    optbar;
}

int x;
/*volatile*/ int y;

volatile(x = y);


More information about the Digitalmars-d mailing list