Get a Reference to an Object's Monitor
    Andrew Wiley 
    wiley.andrew.j at gmail.com
       
    Tue Dec 20 14:20:31 PST 2011
    
    
  
Is there any way to get a reference to an object's monitor? This would
be very useful because a Condition has to be tied to a Mutex, and
since objects already have a reference to a Mutex built in, it doesn't
make much sense to create another (and add another reference to the
class) when the end effect is the same.
Example:
---
class Example {
private:
    Mutex _lock;
    Condition _condition;
public
    this() {
        _lock = new Mutex();
        _condition = new Condition(_lock);
    }
    void methodA() shared {
        synchronized(_lock) {
            // do some stuff
            while(someTest)
                _condition.wait();
        }
    }
    void methodB() shared {
        synchronized(_lock) {
            //do some stuff
            _condition.notifyAll();
        }
    }
}
---
If I could get a reference to Example's monitor, this example becomes:
---
synchronized class Example {
private:
    Condition _condition;
public
    this() {
        _condition = new Condition(this.__monitor);
    }
    void methodA() {
        // do some stuff
        while(someTest)
            _condition.wait();
    }
    void methodB() {
        //do some stuff
        _condition.notifyAll();
    }
}
---
Which is much more fool-proof to write.
    
    
More information about the Digitalmars-d
mailing list