开发者

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 except开发者_开发知识库ion 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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜