Condition variables?

Graham St Jack grahams at acres.com.au
Tue Oct 2 17:09:17 PDT 2007


Janice Caron wrote:
> 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.

It won't deadlock because because the ready.wait call calls 
condition.wait, which atomically unlocks the mutex.


> 
> 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