CGaurdedObject class provides a base class that can be
used for classes that must require some or all of their methods only be run by
one thread at a time. The class incorporates a mutex as private class data. It also
that take and release the mutex respectively.
Below is a typical use pattern for this class:
Example 49-5. Using
CGaurdedObjectclass and must be included by classes that derive from that class.
CGaurdedObjectmust be derived from to be useful. Here we define the
MyClassas a derivation of
CGaurdedObject. What this normally means is that
MyClasshas one or more methods that must be synchronized between threads. The concept of a method that can only run in one thread of execution was developed/discovered by Per Brinch-Hansen, and C.A. Hoare in 1972.
Entermethod of the base class enters the monitor. You can think of this call as your execution flow entering a gate that only admits one execution thread at a time. If a thread is already executing code following an
Entercall any other thread will block until the corresponding
Leavecall is executed. Note that the underying mutex is a recursive mutex so that if a thread already in a monitor needs to call another protected method in the same class it will not block.
Leaveindicates the end of execution of a monitor. If there are threads waiting at an
Enterfor the same object one of them is scheduled for execution, and therefore enteres the monitor.
Note that the monitors implemented by
object global, that is only one thread can execute in an
Leave over the entire object.