views:

87

answers:

2

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.

+6  A: 

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).

James McNellis
Re: Manual unlocking. True, it wasn't an ideal choice. I have used smart pointers for interfaces which let you `.Release()` but will auto release when out of scope. It has been quite a while since I was coding in C++, I may have forgotten/missed something that fits what I was after. Hence this question.
JLWarlow
+2  A: 

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.

Space_C0wb0y
Thanks for the link on `RAII`, I'm now looking at smart pointers to protect a block of memory my code receives.
JLWarlow