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?
scoped_lock<mutex>
with a short name? That makes it easy to type. – Petrie