void MyClass::MyMethod()
{
try{
LockAble.lock();
// do sensitive stuff
if (FaltalError){
// i worry about unlock the lock here
LockAble.unlock();
return;
}
// i worry about unlock the lock here
LockAble.unlock();
}
catch(MyClassException &)
{
// i worry about unlock the lock here
LockAble.unlock();
}
}
If you are finding alternative way to handle the above situation, you are reading the right blog :)..
The aim of writing this blog is explain a way to cope with pair operation such as lock/unlocked, check-in/check-out, acquire/release etc. Would that be cool if just declare only one statement then forget about it? Just look what it should be :)
void MyClass::MyMethod()
{
try{
ScopeLock lock(mLockableObj);
// do sensitive stuff
if (FaltalError){
// i don't worry about unlock the lock here
return;
}
// i don't worry about unlock the lock here
}
catch(MyClassException &)
{
// i don't worry about unlock the lock here
}
}
As above, you might already spotted that there is a class ScopeLock appears, what magic it is to solve it? Well, it just utilize destructor to unlock to lock automatically when that object is out from scope. See below for implementation..
class ScopeLock {
public:
ScopeLock(ILockAble &lockable):mLock(lockable)
{
lock.lock();
}
~ScopeLock()
{
lock.unlock();
}
private:
ILockAble &mLock;
};
That's it! Very easy to adapt to your existing implementation. Just put the starting operation in constructor and exiting operation in destructor. Enjoy coding!
0 comments:
Post a Comment