Condition variables?

David Brown dlang at davidb.org
Wed Oct 3 08:36:43 PDT 2007


On Wed, Oct 03, 2007 at 11:20:06AM -0400, Steven Schveighoffer wrote:

>Interesting concept, so instead of the waiting thread deciding whether the 
>condition is satisfied, the signalling thread decides.  Personally, I'd put 
>a test around the wait statement too in case another thread signalled with a 
>different reason, just to be sure, but I can see how it works now.

This is more like Hoare originally thought of monitors.  My problem with it
is that it puts the logic in a non-obvious place.  It also requires fully
synchronized condition variables (which the example has) where the internal
operations
    unlock mutex
    wait for condition
    lock mutex

are done atomically, and nobody can get in between the wakeup of the wait,
and the relock.  It also generally requires that the signalling of the
condition immediately yield to the one waiting, which isn't how Posix
condition variables are implemented.

So, it is how Hoare thought of it, but not generally how they are used.  I
would suggest not putting the condition into the variable, since it makes
them very different than at least what pthreads users are used to.

Realistically, once we have a functioning condition mechanism, we should
probably implement some higher-level, more useful abstractions.  My
favorite being the 'MVar' (from haskell):

   The MVar is a synchronization variable which can be thought of as a box
   that is either empty or full.  It only has two operations, take and put.

   - put - puts a value into the box.  If the box is already full, it waits.
   - take - takes a value out of the box.  If the box is empty it waits.

They are quite useful.  It can be extended to queues and other types of
things.

Dave



More information about the Digitalmars-d mailing list