I'm looking for code shortening idea. I'm using boost::scoped_lock
to lock a boost::mutex
but I want to shorten the amount of code I'm writing.
Currently I have a mutex
defined in my class and the member field called _sync
. When I want to lock, I have to write:
scoped_lock<mutex> lock(_sync);
The tricky part is that this is a scoped lock, so I assume that if I write a static function to return the scoped_lock, then it will unlock as soon as it gets out of the function scope of the static function:
static scoped_lock<mutex> lock(mutex& sync)
{
return scoped_lock<mutex>(sync);
}
This approach would make it really easy to type:
public void Object::modify()
{
lock(_sync); // <-- nice and short! ;)
// do something to modify the object
//..
// the mutex is unlocked when we leave the scope of modify
}
Is my assumption correct? Will the scoped_lock
unlock immediately when it's returned by my static function?
#define LOCK(a) scoped_lock<mutex> scopedLockVar(a)
public void Object::modify()
{
LOCK(_sync); // <-- nice and short! ;)
// do something to modify the object
//..
// the mutex is unlocked when we leave the scope of modify
}
You should use a safe name for the define... The compiler just uses find and replace for defines...