Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic locking/unlocking using scope in C++ (from C# background)

I've been using C# for the last few years and I am currently bug fixing in C++. In C# I could use lock on an object to make my code thread safe with:

lock(lockObject)
{
    // Do some work
}

This would unlock the lockOject if there was an exception within the // Do some work

Is there something similar in C++? At the moment I can think of either:

// Code
{
    AutoLock lock(lockObject);
    // Do some work
}
// More Code

But I don't like the curly braces just to scope my AutoLock. At the moment I'm doing:

AutoLock lock(lockObject);
// Do some work
lock.Unlock();

And letting exception unwinding release the lock if there's an exception in //Do some work.

What I'm doing at the moment works, but I'm wondering if there's a better way, thanks.

like image 325
John Warlow Avatar asked Jul 19 '10 15:07

John Warlow


2 Answers

But I don't like the curly braces just to scope my AutoLock.

That's how it's done in C++.

Note that you don't need to have a separate scope block for each AutoLock; the following is fine too:

{
    AutoLock lock1;
    AutoLock lock2;
    // more code goes here
} // lock2 gets destroyed, then lock1 gets destroyed

It doesn't have to be a separate scope block either; if you are locking something in a function and don't need it to be unlocked until the function returns, then you can simply use the function scope to constrain the lock . Likewise, if you are locking something during each iteration in a loop block, you can use the loop's scope block to constrain the lock.

Your approach of manually unlocking the mutex when you are done with it is fine, but it's not idiomatic C++ and isn't as clear. It makes it harder to figure out where the mutex is unlocked (not much harder, perhaps, but harder than it needs to be).

like image 117
James McNellis Avatar answered Nov 09 '22 22:11

James McNellis


Your second version is just fine. Consider splitting your method if you have too many braces that are just for scoped locking. Read up on RAII, that is the general pattern behind this technique, and it can be applied to every kind of resource management.

like image 2
Björn Pollex Avatar answered Nov 09 '22 22:11

Björn Pollex