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
}
//1 The declaration of an RWTLockGuard<RWMutexLock> instance invokes a constructor that acquires the mutex passed as an argument.
//2 The RWTLockGuard<RWMutexLock> instance is automatically destroyed when it goes out-of-scope—upon exit from the block where it was declared. The RWTLockGuard<RWMutexLock> destructor releases the mutex that was previously acquired. The guard instance is also destroyed if an exception occurs within this block, thus insuring that the mutex is always released.
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.