Condition Mutexes
Graham St Jack
Graham.StJack at internode.on.net
Tue Oct 20 20:48:33 PDT 2009
On Wed, 21 Oct 2009 00:56:13 +0000, dsimcha wrote:
> I'm messing around w/ core.sync. Does anyone know what I'm doing wrong
> in this program? It just hangs. If I could figure out ()##$) condition
> mutexes (right now, I'm using busy spinning), I might have a decent
> implementation of parallelForeach over ranges.
>
> import core.sync.mutex, core.sync.condition, core.thread, std.stdio;
>
> __gshared Condition condition;
>
> void waitThenPrint() {
> condition.wait();
> writeln("FOO");
> }
>
> void main() {
> condition = new Condition( new Mutex() ); auto T = new
> Thread(&waitThenPrint);
> T.start();
> condition.notify(); // Never wakes up and prints FOO.
> }
There are a few problems. The most serious is that you have to lock the
mutex before calling condition.wait(). The underlying operating-system
stuff atomically
This means that the mutex needs to be an attribute of the class, and
waitThenPrint() should be more like this:
void waitThenPrint() {
synchronized(myMutex) {
condition.wait();
}
writeln("FOO");
}
While it isn't strictly necessary in this case, you should also:
Put the condition.notify() call into a synchronized(myMutex) block.
When some state variables are involved in the condition, you should do
something like this:
void waitThenPrint() {
synchronized(myMutex) {
while (state_not_right()) {
condition.wait();
}
}
writeln("FOO");
}
and
synchronized(myMutex) {
set_state_to_right();
condition.notify();
}
More information about the Digitalmars-d
mailing list