Using RWTRecursiveLock
In Example 36, the date function must lock the entire Date instance to prevent partial changes while the day, month, and year accessor functions acquire and release the mutex to protect their individual members. The recursive mutex allows the date function to use the day, month, and year accessors without producing deadlock.
Example 36 ā€“ Preventing deadlock with a recursive mutex
class Date {
private:
RWTRecursiveLock<RWMutexLock> mutex_;
unsigned int day_;
unsigned int month_;
int year_;
...
public:
unsigned int day() const {
RWTRecursiveLock<RWMutexLock>::LockGuard lock(
const_cast<Date*>(this)->mutex_);
return day_;
}
void day(unsigned int newDay) {
RWTRecursiveLock<RWMutexLock>::LockGuard lock(
const_cast<Date*>(this)->mutex_);
day_ = validateDay(newDay);
}
unsigned int month() const {
RWTRecursiveLock<RWMutexLock>::LockGuard lock(
const_cast<Date*>(this)->mutex_);
return month_;
}
void month(unsigned int newMonth) {
RWTRecursiveLock<RWMutexLock>::LockGuard lock(
const_cast<Date*>(this)->mutex_);
month_ = validateMonth(newMonth);
}
int year() const {
RWTRecursiveLock<RWMutexLock>::LockGuard lock(
const_cast<Date*>(this)->mutex_);
return year_;
}
 
void year(int newYear) {
RWTRecursiveLock<RWMutexLock>::LockGuard lock(
const_cast<Date*>(this)->mutex_);
year_ = validateYear(newYear);
}
RWCString date() const {
RWTRecursiveLock<RWMutexLock>::LockGuard lock(
const_cast<Date*>(this)->mutex_);
char buf[11];
sprintf(buf,ā€%02d-%02d-%04dā€,month(),day(),year());
return RWCString(buf);
}
...
};