Re: code pattern for locking & unlocking
Am 25.11.2010 23:48, schrieb Daniel Anderson:
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.
Yep, that is the perfect scenario for the RAII (resource acquisition is
initialization) idiom. The new C++0x standard library provides for this
80% bread-and-butter business the so-called lock_guard class which has
exactly the simple constructor/destructor API as your type.
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.
Yes, in some situations we have these kinds of code flow disruptions
that are hard to get rid of. For such situations the C++0x library
provides the lock type unique_lock which is able to release and to
re-acquire a new lock.
I would like to have something like the using keyword in c#.
Is there a way to fake it in C++ ?
Not extremely much more. You may consider the Scope Guard as a more
general form:
http://www.drdobbs.com/184403758
The Loki library
http://loki-lib.sourceforge.net/index.php?n=Main.HomePage
contains also this component.
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 ?
Looks OK to me.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]