Slanted castle with condition

I want to create a fixed lock, but I need 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 the condition is true, I want to have a mutex lock, but in scope. I know that I can use a simple .lock and at the end of the area use .unlock, but I have a lot of way back. I can also create some Visibility SynchronizationGuard and a destructor called mutex unlock, but this is not a clean solution. Some tips?

Sincerely.

+4
source share
2 answers

Use the ternary operator.

boost::mutex::scoped_lock lock = lockRequired ? 
boost::mutex::scoped_lock(Mutex) : boost::mutex::scoped_lock();

Or just use the swapprovided.

boost::mutex::scoped_lock lock;
if (lockRequired)
{
   boost::mutex::scoped_lock lock_(Mutex);
   lock.swap(lock_);
}

Or just create a lock with defer_lock_t, and then call the function lock.

boost::mutex::scoped_lock lock(Mutex, boost::defer_lock);
if (lockRequired)
{
   lock.lock();
}
+6

:

#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
}

std::unique_lock, std::lock_guard

adopt_lock.

+3

All Articles