Condition variables?

Steven Schveighoffer schveiguy at yahoo.com
Tue Oct 2 08:21:21 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.

Conditions are supported by an atomic "unlock mutex and wait" operation. 
For example,  in windows, by the SignalObjectAndWait function.  You are 
basically saying: unlock this mutex and wait for the condition to be 
signaled, then lock the mutex and return.  The operation has to be atomic so 
that the thread can't be switched out of context just after unlocking and 
miss the signal.  It is actually invalid to wait on a condition without 
having the mutex locked.

So the code above has to do something special by unlocking the object before 
waiting using an atomic operation.  I think this requires some language 
support.

BTW, I'm not sure what the ready(count > 0) function does?  Can someone 
explain it?  It appears that it is the signal, but I'm not sure why the 
condition is required.

-Steve 





More information about the Digitalmars-d mailing list