Wednesday, July 2, 2008

Lock questions

Given the following C++ code, what ways can release not be called?

Lock lock; //global

void function() {
lock.grab();
...
lock.release();
}

1) a return statement is called
2) a exception is thrown but caught in a calling function

How would you guarantee that release() is called?

Since destructors are always called on local objects, construct a wrapper class that holds a reference to the lock and call release() on that lock in the wrapper class's destructor. Thus, when the function goes out of scope for either of the above cases, the wrapper class's destructor will always get called.

class LockWrapper {
private:
Lock& lock;
public:
LockWrapper(Lock& _lock) : lock(_lock) {}
~LockWrapper() { lock.release(); }
};

Lock lock; //global

void function() {
LockWrapper wrapper(lock);
lock.grab();
...
lock.release();
}

No comments: