digitalmars.D.learn - Is synchronized(mutex) == mutex.lock()?
- Heywood Floyd (15/15) Jul 14 2010 Hi!
- Steven Schveighoffer (17/30) Jul 15 2010 Almost, this is more equivalent:
- Heywood Floyd (3/46) Jul 15 2010 Cool, love it! Thanks!
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
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
Steven Schveighoffer Wrote:On Wed, 14 Jul 2010 23:22:20 -0400, Heywood Floyd <soul8o8 gmail.com> wrote:Cool, love it! Thanks! /HFHi! 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