www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Is synchronized(mutex) == mutex.lock()?

reply Heywood Floyd <soul8o8 gmail.com> writes:
Hi!

Breakfast toast: Is there any chance a) and b) below are identical in what they
do?


auto mutex = new Mutex();
auto cond = new Condition(mutex);

// a)
synchronized(mutex){
   cond.wait();
}

// b)
mutex.lock();
   cond.wait();
mutex.unlock();


I was sprinkling my code with mutex.lock/unlock (for fun) when suddenly I
realized that, hey, maybe synchronized would work just as well, and be even
more fun? (If that's even possible.)

BR
/HF
Jul 14 2010
parent reply "Steven Schveighoffer" <schveiguy yahoo.com> writes:
On Wed, 14 Jul 2010 23:22:20 -0400, Heywood Floyd <soul8o8 gmail.com>  
wrote:

 Hi!

 Breakfast toast: Is there any chance a) and b) below are identical in  
 what they do?


 auto mutex = new Mutex();
 auto cond = new Condition(mutex);

 // a)
 synchronized(mutex){
    cond.wait();
 }

 // b)
 mutex.lock();
    cond.wait();
 mutex.unlock();

Almost, this is more equivalent: { mutex.lock(); scope(exit) mutex.unlock(); cond.wait(); } But yes, the mutex object implements the monitor interface, and replaces its own monitor object with a pointer to itself. For something really nifty, you can tell mutex to be the monitor object of *any* other object :) Unfortunately, I can't point you at the docs, cause they dont exist yet, but this will do it: class C{} auto c = new C; auto m = new Mutex(c); // now synchronizing on c is the same as locking m -Steve
Jul 15 2010
parent Heywood Floyd <soul8o8 gmail.com> writes:
Steven Schveighoffer Wrote:

 On Wed, 14 Jul 2010 23:22:20 -0400, Heywood Floyd <soul8o8 gmail.com>  
 wrote:
 
 Hi!

 Breakfast toast: Is there any chance a) and b) below are identical in  
 what they do?


 auto mutex = new Mutex();
 auto cond = new Condition(mutex);

 // a)
 synchronized(mutex){
    cond.wait();
 }

 // b)
 mutex.lock();
    cond.wait();
 mutex.unlock();

Almost, this is more equivalent: { mutex.lock(); scope(exit) mutex.unlock(); cond.wait(); } But yes, the mutex object implements the monitor interface, and replaces its own monitor object with a pointer to itself. For something really nifty, you can tell mutex to be the monitor object of *any* other object :) Unfortunately, I can't point you at the docs, cause they dont exist yet, but this will do it: class C{} auto c = new C; auto m = new Mutex(c); // now synchronizing on c is the same as locking m -Steve

Cool, love it! Thanks! /HF
Jul 15 2010