Condition Mutexes

dsimcha dsimcha at yahoo.com
Wed Oct 21 12:29:25 PDT 2009


== Quote from Jason House (jason.james.house at gmail.com)'s article
> dsimcha Wrote:
> > == Quote from Bartosz Milewski (bartosz-nospam at relisoft.com)'s article
> > > dsimcha Wrote:
> > > > void main() {
> > > >     condition = new Condition( new Mutex() );
> > > >     auto T = new Thread(&waitThenPrint);
> > > >     T.start();
> > > >     condition.notify();  // Never wakes up and prints FOO.
> > > > }
> > > Your program terminates immediately after sending the notification. You need to
> > stall the exit until the other thread has a chance to wake up.
> >
> > Thanks.  I've implemented this, along w/ one other suggestion from another poster.
> >  Here's the new program.  It still doesn't work.  Has anyone successfully used
> > core.sync.condition from druntime *on D2, not the Tango version on D1*?  If it
> > works, then it should be better documented so people who aren't already threading
> > gurus can figure out how to use it.  If it doesn't work, then as soon as I can
> > confirm that I'm not the problem, I'll go file a bug report.
> >
> > Bartosz, since you're a threading guru, could you please write a simple test
> > program using core.sync.condition and see if it works, and if not either file a
> > bug report or let me know?
> >
> > import core.sync.mutex, core.sync.condition, core.thread, std.stdio;
> >
> > __gshared Condition condition;
> > __gshared Mutex mutex;
> >
> > void waitThenPrint() {
> >     mutex.lock;
> >     condition.wait();
> >     mutex.unlock;
> >     writeln("FOO");
> > }
> >
> > void main() {
> >     mutex = new Mutex;
> >     condition = new Condition(mutex);
> >     auto T = new Thread(&waitThenPrint);
> >     T.start();
> >     condition.notify();  // Never wakes up and prints FOO.
> >     T.join;
> > }
> You should lock condition before calling notify. Even if you did that, you have
a race for which thread gets the lock first. If the main thread gets it, the
spawned thread will never receive the notify and hang forever.

Thanks, but at a more general level, where can I find documentation on how to use
conditions properly?  I realize that I have absolutely no fundamental
understanding of how they work or what assumptions they make, but it seems like
there is very little written material on this, either for the general case or for
the specific case of core.sync.  For example, for some reason I assumed that a
condition's methods would be already synchronized internally.



More information about the Digitalmars-d mailing list