Condition variables?

Janice Caron caron800 at googlemail.com
Tue Oct 2 00:27:44 PDT 2007


On 10/2/07, Graham St Jack <grahams at acres.com.au> wrote:
> You use it like this (incomplete pseudo-code):
>
> class ProtectedQueue(T) {
>      Condition ready;
>      int count;
>
>      this() {
>          ready = new Condition(this);
>      }
>
>      synchronized void add(T item) {
>          add_item_to_queue;
>          ++count;
>          ready(count > 0);
>      }
>
>      synchronized T remove() {
>          ready.wait;       // wait until count is > 0
>          --count;
>          ready(count > 0);
>          return remove_item_from_queue;
>      }
> }

I do believe that would deadlock. If thread A was waiting inside a
synchronized block, then thread B would never be able to enter the add
function, and hence would never be able to trigger the condition.

Incidently, the same psuedo-code written using Events instead of
Conditions (with the dealock still in place) would be:

class ProtectedQueue(T) {
    Event ready;
    int count;

    this() {
        ready = new Event;
    }

    synchronized void add(T item) {
        add_item_to_queue;
        ++count;
        ready.signal;
    }

    synchronized T remove() {
        ready.wait;       // wait until count is > 0 -- not a good
idea inside synchronized!
        --count;
        if (count > 0) ready.signal;
        return remove_item_from_queue;
    }
}



More information about the Digitalmars-d mailing list