synchronized / cond.wait

Stefan Rohe Stefan.Rohe at funkwerk-itk.com
Tue Mar 31 06:37:33 PDT 2009


Hi all,

could someone explain us this "synchronize" behaviour? We do not understand
it.

Two Threads.
First Thread should wait for a condition. This we do in a
synchronized(mutex) block.
The second Thread broadcasts then a notify. This also in a synchronized
block, synchronizing on the same mutex. This should be impossible!? Does the
condition.wait modify the Mutex object so that it after this has another
address?


import tango.core.Thread;
import tango.core.sync.Condition;
import tango.core.sync.Mutex;
import tango.io.Console;

Object lock;
Mutex mutex;
Condition condition;

void print(char[] msg) {
    synchronized (lock) {
        Cout(msg).newline;
    }
}

void produce() {
    while (true) {
        print("notify");
        synchronized (mutex) {
            print("notify lock");
            condition.notify;
            print("notify unlock");
        }
        Thread.sleep(1.0);
    }
}

void consume() {
    while (true) {
        synchronized (mutex) {
            print("wait lock");
            condition.wait;
            print("wait unlock");
        }
        print("notified");
    }
}

void main() {
    lock = new Object;
    mutex = new Mutex;
    condition = new Condition(mutex);
    (new Thread(&consume)).start;
    (new Thread(&produce)).start;
}

Output:
wait lock
notify
notify lock
notify unlock
wait unlock
notified
...


best regards
  Stefan




More information about the Digitalmars-d-learn mailing list