Using a Try-Catch Block
A potential problem with this second implementation is that if one of the iostream operations produces an exception, the mutex.release() statement is not executed, leaving the mutex locked forever.
One way to fix this problem is to add a try-catch block around the output operation and code a second mutex release in the catch block:
Example 27 – Using a try-catch block to ensure the mutex is released
void hello(void)
{
// Declare a static mutex instance that will
// be shared by all threads calling this function
static RWMutexLock mutex;
 
for(int i=0;i<100;i++) {
 
// Acquire mutex to block other threads
mutex.acquire();
 
try {
cout << "Hello” << "World!” << endl;
}
catch(...) {
// Exception occurred!
// Release the mutex and rethrow
mutex.release();
throw;
}
// Release the mutex so other threads can say "hello”
mutex.release();
}
}
With this code, the mutex is released, even if an exception is thrown by an iostream operation. (The mutex state might not be important once an exception has occurred, but assume that it is for the purpose of this discussion.)
This solution is sufficient for a simple example, but if unique handlers for several different exceptions are required, you must remember to code the mutex release in each catch block that you define. This can be cumbersome and can introduce difficult-to-detect coding mistakes.