Reputation: 10537
boost::recursive_mutex m;
m.lock();
versus
boost::lock_guard<boost::recursive_mutex> lock( mutex_ );
Is there an advantage to use the first Form? Does the second form only provide RAII mecanism, or are there others advantages ?
Upvotes: 2
Views: 876
Reputation: 35459
The two forms are not equivalent in the least. Here's what's equivalent* to the second form:
boost::recursive_mutex m;
m.lock();
try {
// ...
} catch(...) {
m.unlock();
throw;
}
m.unlock();
This is what you call "only" providing RAII: avoiding hideous boilerplate to provide the same level of correctness.
*: with caveats; see other answers & comments
Upvotes: 2
Reputation: 20083
The advantage of using lock_guard is that it will release the lock when it goes out of scope. This eliminates the need to manually release the lock and reduces the chance of forgetting to do so.
boost::recursive_mutex mylock;
{
boost::lock_guard<boost::recursive_mutex> lock( mylock );
// do something
if(false == do_something())
{
return; // "lock" goes out of scope and unlocks 'mylock' from it's destructor.
}
}
// "lock" has gone out of scope and unlocked 'mylock' from it's destructor.
Upvotes: 5