Using a monitor condition

If a monitor member function needs to verify that a certain condition exists before accessing the monitor data, it can use a private monitor condition member to represent the condition. For example, suppose TResourceAllocator is a monitor that manages a resource of type TSomeResourceType. A private member fResourceAvailable of type TMonitorCondition can represent the availability of the resource. The monitor's Allocate() member function might look like this:

      TSomeResourceType TResourceAllocator::Allocate()
      {
          TMonitorEntry entry(&fMonitorLock);     // enter monitor
      
          while (resource is not available)
              fResourceAvailable.Wait();          // exit monitor and block
      
          // automatically reenter the monitor
          // allocate the resource...
      
          return (the resource);                  // automatically leave the monitor
      }
While Allocate() is blocked on the condition, some other thread must detect a change in the condition and notify the allocating thread. In this example, the allocator's Free() member function might look like this:

      void TResourceAllocator::Free(TSomeResourceType *theResource)
      {
          TMonitorEntry entry(&fMonitorLock);     // enter monitor
      
          // free theResource...
      
          if (resource was not available before we freed theResource)
              fResourceAvailble.Notify();         // unblock Allocate()
      
          return;                                 // automatically leave the monitor
      }
Notify() unblocks exactly one waiting thread. Sometimes it's desirable to unblock all threads waiting on a condition, such as when an error occurs. In this example, if Free() detected that the resource pool was corrupted, it could unblock all threads waiting on the condition by calling the monitor condition object's Broadcast() member function before throwing an exception.


[Contents] [Previous] [Next]
Click the icon to mail questions or corrections about this material to Taligent personnel.
Copyright©1995 Taligent,Inc. All rights reserved.

Generated with WebMaker