synchronized { }

Sean Kelly sean at invisibleduck.org
Mon Jun 30 13:57:48 PDT 2008


== Quote from torhu (no at spam.invalid)'s article
> Steven Schveighoffer wrote:
> > In any case, Tango avoids needing this statement by making mutexes fully
> > accessible objects.  If you need a mutex without having it attached to an
> > object, it's easy:
> >
> > Mutex m = new Mutex;
> >
> > synchronized(m)
> > {
> > }
> Isn't that the same as doing this?
> ---
> Object m = new Object;
> synchronized(m)
> {
> }
> ---

No.  Mutexes in Tango can be set as the monitor for any object, and
are in fact their own monitors.  So synchronized(m) actually locks the
Mutex, not a separate monitor object associated with the Mutex object.
You can just as easily do this:

class C
{
    this(Mutex x)
    {
        m = x;
        setMonitor(this, m);
    }

    Mutex m;

    void fn()
    {
        // the following are all equivalent
        synchronized {}
        synchronized(this) {}
        synchronized(m) {}
    }
}

Ore read-write mutexes:

ReadWriteMutex m;

synchronized(m.reader) {}
synchronized(m.writer) {}


Sean



More information about the Digitalmars-d mailing list