Re: code pattern for locking & unlocking
On Nov 25, 5: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.
I guess it's a matter of taste. For me the curly braces are very
natural way of denoting the block.
something like:
struct Lock
{
Lock(Mutex& mtx) mtx_(mtx) { mtx.lock(); }
~Lock() { mtx_.unlock(); }
operator bool() { return true;}
};
Putting aside the errors in the code above, the only reason "operator
bool" exists in the class is to make if() construct possible, it's not
required for Lock proper functionality, which violates a good design
rule: make interface complete and minimal.
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++ ?
That's one of the common mistakes people switching to another language
do -- is trying to fake what they are used to in a different language.
That usually causes grief for everybody who has to deal with that
code. Each language commands its own style, the only way to write good
code is to learn and use it.
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))
{
That assumes that Lock is copy-constructible or move-constructible,
which it's not -- because mutex is neither copy-constructible nor move-
constructible. Allowing that would lead to unsafe code causing
deadlocks or races.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]