Get a Reference to an Object's Monitor
Sean Kelly
sean at invisibleduck.org
Tue Dec 20 21:15:15 PST 2011
You still need to create a Mutex. The default object monitor isn't compatible with Condition. But you don't need to hold a reference to it if you make it the object's monitor. See the docs for Mutex.
Sent from my iPhone
On Dec 20, 2011, at 2:20 PM, Andrew Wiley <wiley.andrew.j at gmail.com> wrote:
> 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