Building Monitors
A monitor is a passive object that has a synchronized interface for accessing a shared resource. A simple form of monitor can be constructed by encapsulating a resource or data in a C++ class that also includes a mutex. Each member function that gives access to the resource or data uses the mutex to synchronize or serialize the access operations.
In
Example 29, a simple monitor class is constructed to implement a multithread-safe counter.
Example 29 – Implementing a multithread-safe counter
#include <rw/sync/RWMutexLock.h>
class Counter {
private:
RWMutexLock mutex;
int count_;
public:
Counter(int count=0) : count_(count) {}
Counter& operator++(void)
{
RWMutexLock::LockGuard guard(mutex);
count_++;
return *this;
}
Counter& operator--(void)
{
RWMutexLock::LockGuard guard(mutex);
count_--;
return *this;
}
operator int(void) const
{
RWMutexLock::LockGuard guard(mutex);
return count_;
}
};
In this example, each member function that accesses the count member first acquires the mutex to insure that other threads do not simultaneously attempt to change the count value.
NOTE: Instead of the
RWTLockGuard class, this example uses the public type
LockGuard that is defined by the
RWMutexLock class. All of the Synchronization package classes have pre-defined guard types.