Re: code pattern for locking & unlocking
On Nov 25, 11:48 pm, Daniel Anderson <woni...@gmail.com> wrote:
Hi!
I often have to acquire locks and release them after I'm finished with
them.
I use constructor/destructor to acquire & release locks. everything
works fine.
sometime I must acquire a lock for few instructions, then release it
in the middle of a big function. I use braces to get timely
destructors, but I find the "middle of nowhere" braces kind of
embarrassing.
something like:
struct Lock
{
Lock(Mutex& mtx) mtx_(mtx) { mtx.lock(); }
~Lock() { mtx_.unlock(); }
operator bool() { return true;}
};
void someFunc()
{
// do some stuff
...
// now time to update share data
{
Lock myLock(data_mutex);
//use locked data
....
} // destructor called
// do more stuff
...
}
I would like to have something like the using keyword in c#.
Is there a way to fake it in C++ ?
for now I'm using an if to do it.
void someFunc()
{
// do some stuff
...
// now time to update share data
if (Lock myLock = Lock(data_mutex))
{
//use locked data
....
} // Unlock done by destructor
// do more stuff
...
}
Is it good programming ?
Is there a better way ?
Frankly, I find the "if" worse than a "standalone" block. It obscures
intention of the code (there an "if, but there is no "condition" to
enter the "if" block).
I don't know of a better way than what you've shown, and I don't
consider hanging blocks bad. If you are so bothered, there is nothing
wrong in creating a function specifically for your block. Imagine:
void SynchronizedPart(type1& p1, type2& p2, type3& p3)
{
lock l(mutex);
abuse(p1, p2, p3);
}
void someFunc()
{
// do stuff...
SynchronizedPart(d1, d2, d3);
// do more stuff
}
This arguably even reads better and you can be pretty sure that you'll
normally get no runtime overhead whatsoever (optimization will see
that there's only one use of SynchronizedPart and will inline it).
Also, with C++0x, perhaps some clever use of lambdas can even automate
creation of "synchronized" stuff, and I would be surprised if someone
didn't already do it e.g. with boost::lambda.
Goran.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]