I want to create scoped lock, but I want something like:
{
if(lockRequired)
boost::mutex::scoped_lock(Mutex); //After this line we go out of scope
/* Here I also want to have Mutex */
}
if condition is true I want to have lock mutex but in level up scope. I know that I can use simple .lock and in the end of scope use .unlock but I have many return path. I can also create some SynchronizationGuard in scope and whed destructor is called unlock mutex but it's not clean solution. Some advices ?
Best regards.
Use ternary operator.
boost::mutex::scoped_lock lock = lockRequired ?
boost::mutex::scoped_lock(Mutex) : boost::mutex::scoped_lock();
Or just use swap
under condition.
boost::mutex::scoped_lock lock;
if (lockRequired)
{
boost::mutex::scoped_lock lock_(Mutex);
lock.swap(lock_);
}
Or just construct lock with defer_lock_t
and then call lock
function.
boost::mutex::scoped_lock lock(Mutex, boost::defer_lock);
if (lockRequired)
{
lock.lock();
}
You can construct the lock deferred:
#include <boost/thread.hpp>
int main() {
boost::mutex mx;
boost::mutex::scoped_lock sl(mx, boost::defer_lock);
if (condition)
sl.lock();
// sl will unlock on end of scope
}
Also works for std::unique_lock
, std::lock_guard
and corresponding boost types
Analogously there's the adopt_lock
tag type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With