Re: code pattern for locking & unlocking
On Nov 26, 8:19 pm, Gene Bushuyev <408...@gmail.com> wrote:
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.
well, yes in the example I've shown bool always return true, but it
could be use in case lock could not be acquired
which would allow an else part.
on this I have not decided if I should throw in the constructor or use
the else part. I will probably play with it a bit before deciding
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.
I am not switching from c#, I was using an example. I find in this
case the C# syntax clearer.
Language do not command style, it is people who define style, language
is only a tool
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.
yes, but it happen that my compiler is getting rid of the copy
contructor and directly construct my object as if I was doing:
if (Lock myLock(data_mutex))
I know it is not portable, but this is not the point of this post.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]