Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scoped lock with if condition

Tags:

c++

boost

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.

like image 643
DDD Avatar asked Jan 08 '23 21:01

DDD


2 Answers

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();
}
like image 200
ForEveR Avatar answered Jan 17 '23 02:01

ForEveR


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.

like image 26
sehe Avatar answered Jan 17 '23 00:01

sehe