Why is scoped_lock recommended?
This is the same reason as raiI idiom is becoming popular: You can indeed pack mutex that will be unlocked when you leave the execution range in any case.
Note: not only do you forget to call unlock (): After Your mutex is locked, an exception may also be thrown. The unlock CALL statement you write may never be executed, even inLock ()
AndThe same is true if no return statement is returned between unlock ().
.
M. lock () // M is a mutex //... foo (); // If throw is up in this function, your mutex will be locked forever //... m. unlock ()
YourScoped_lock
The Destructor is always automatically called when the stack is expanded. This ensures that the associated mutex is always released.
{Boost: scoped_lock lock (m); // M is a mutex //... foo (); // If throw is up, your raiI wrapper will unlock mutex //...}
In addition, this will increase the readability of your code. You do not need to add an unlock before each return statement.
Boost -- scoped_lock v. S. mutex lock/unlock -- why is scoped_lock recommended?