Using Guards
The guard classes use the “resource acquisition is initialization” idiom where the object constructor is used to acquire a resource, and its destructor is used to release an acquired resource. The
RWTLockGuard template class uses this idiom for automatic acquisition and release of various synchronization resources, including instances of
RWMutexLock.
To use
RWTLockGuard, declare and initialize a named instance of the class within the code block that the mutex is intended to protect, as in
Example 28.
Example 28 – Using a guard to automatically acquire and release a mutex
void hello(void)
{
static RWMutexLock mutex;
for(int i=0;i<100;i++) {
RWTLockGuard<RWMutexLock> guard(mutex); // 1
cout << "Hello” << "World!” << endl;
} // 2
}
This version of hello() is functionally equivalent to the previous implementation, but is easier to write and easier to understand than the previous version that used the try-catch block.
In addition to the lock guard class, the Synchronization package also has
try-lock and
unlock guard classes. For more information on each of these guard classes see
The Guard Classes.