Thread overview | |||||
---|---|---|---|---|---|
|
July 15, 2010 Is synchronized(mutex) == mutex.lock()? | ||||
---|---|---|---|---|
| ||||
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 |
July 15, 2010 Re: Is synchronized(mutex) == mutex.lock()? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Heywood Floyd | 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
|
July 15, 2010 Re: Is synchronized(mutex) == mutex.lock()? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Steven Schveighoffer | 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
|
Copyright © 1999-2021 by the D Language Foundation