Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to try_lock on a boost::unique_lock<boost::mutex>

As per title, how to try_lock on a boost::unique_lock ?

I've this code:

void mySafeFunct()
{
    if(myMutex.try_lock() == false)
    {
        return -1;
    }

    // mutex ownership is automatically acquired

    // do stuff safely

    myMutex.unlock();
}

Now I'd like to use a unique_lock (which is also a scoped mutex) instead of the plain boost::mutex. I want this to avoid all the unlock() calls from the function body.

like image 940
Gianluca Ghettini Avatar asked Dec 01 '22 04:12

Gianluca Ghettini


1 Answers

You can either defer the locking with the Defer constructor, or use the the Try constructor when creating your unique_lock:

boost::mutex myMutex;
boost::unique_lock<boost::mutex> lock(myMutex, boost::try_lock);

if (!lock.owns_lock())
    return -1;

...
like image 88
jelford Avatar answered Dec 29 '22 18:12

jelford