synchronized vs. C volatile

Sean Kelly sean at invisibleduck.org
Mon Aug 9 09:48:14 PDT 2010


SK Wrote:

> On Mon, Aug 9, 2010 at 6:25 AM, dsimcha <dsimcha at yahoo.com> wrote:
> > == Quote from SK (sk at metrokings.com)'s article
> >> Does 'synchronized' mean the exact same thing as the C 'volatile'
> >> qualifier when applied to basic types?
> >> As in:
> >> synchronized int x;
> >
> > They're completely different.  synchronized is basically a scoped mutex and
> > applies to a statement, not a variable declaration.  I have no idea what your
> > example does, but it probably shouldn't even compile.  Volatile just prevents
> > certain compiler optimizations that can interfere with updates to a variable from
> > other hardware besides the CPU and is useful for things like device drivers.
> >
> >
> 
> Sounds right to me too.  But the compiler warns about deprecated
> 'volatile'.  Is the warning a mistake?  Volatile has an important
> place in a systems language and I'd rather not mess with tradition
> here.

volatile is present in D1 but was deprecated in D2 in favor of shared.  I actually liked D1 volatile, but I think I was among the few.  In short, D1 volatile did the bare minimum to ensure that correct multithreaded code could be implemented by constraining compiler optimizations across volatile statement boundaries.  For correct synchronized behavior, memory barriers still might have to be added however.

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.


More information about the Digitalmars-d mailing list