Using a Guard Class
Try-catch blocks can be added to correct this problem, but it is much easier to use a guard class instance to automatically acquire and release the mutex at construction and destruction.
By using the lock guard defined by the RWMutexLock class, this example can be rewritten as in Example 33.
Example 33 – Using a guard to acquire and release a mutex
template <class T>
class Queue {
private:
RWMutexLock mutex_;
RWTValSlist<T> list_;
public:
void enqueue(const T& t) {
RWMutexLock::LockGuard lock(mutex_);
list_.append(t);
}
T dequeue(void) {
RWMutexLock::LockGuard lock(mutex_);
return list_.removeFirst(t);
}
}
In this version, the mutex is always released, even if an exception is thrown by one of the list members or by the template parameter class.