Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using unique_lock in new scope equivalent to unlock call at the end of work with shared resource?

I have seen a lot of examples of code when developer uses std::unique_lock in new scope for automatically unlocking mutex:

...
// do some staff
{
  std::unique_lock<std::mutex> lock(shared_resource_mutex);
  // do some actions with shared resource
}
// do some staff
...

In my opinion it would be better to implement this behaviour using method unlock from std::unique_lock API in this way:

...
// do some actions
std::unique_lock<std::mutex> lock(shared_resource_mutex);
// do some actions with shared resource
lock.unlock();
// do some actions
...

Are these two fragments of code equivalent? For what purpose developers use the first variant? Maybe to emphasize (using parentheses) code that can not be executed parallel?

like image 706
Igor Avatar asked Dec 13 '22 15:12

Igor


1 Answers

When the object is destroyed at the end of the scope, the lock is released. That's the whole point of RAII.

The good thing about using RAII is that you cannot forget to unlock and it doesn't matter how you leave the scope. If an exception is thrown for example, the lock will still be released.

If all you need is lock at construction and unlock at destruction, then std::scoped_lock is an even simpler/more appropriate class to use though.

like image 162
Jesper Juhl Avatar answered Jan 18 '23 17:01

Jesper Juhl