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