Condition variables?

David Brown dlang at davidb.org
Tue Oct 2 00:34:00 PDT 2007


On Tue, Oct 02, 2007 at 09:56:58AM +0930, Graham St Jack wrote:

> I have tried to get conditions into the language before, without success 
> (or even much interest from others). I find Conditions absolutely essential 
> in multi-threaded applications, and can't understand why they are missing.

On Linux, there isn't much else you can do.  You can use events on Windows
and such, but I think it is hard to get event-based programming right.

> 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've normally seen condition code where the wait decision is made as part
of the wait, not as part of the signal.  It allows different waiters to
have different conditions (although having multiple waiters is complicated,
and requires access to pthread_cond_broadcast).

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

    synchronized T remove()
    {
      while (count == 0)
        ready.wait
      count--;
      return remove_item_from_queue;
    }

When I get to needing threads, I'll definitely look into your condition
code, and see if I can get it to work.  It shouldn't be too complicated, I
just wasn't sure how to get access to the object's monitor.

Is it possible to make 'this' synchronized?

Dave



More information about the Digitalmars-d mailing list