Condition Mutexes

Jason House jason.james.house at gmail.com
Wed Oct 21 12:12:45 PDT 2009


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.



More information about the Digitalmars-d mailing list