简体   繁体   English

如何在boost :: unique_lock上尝试try_lock <boost::mutex>

[英]How to try_lock on a boost::unique_lock<boost::mutex>

As per title, how to try_lock on a boost::unique_lock ? 根据标题,如何在boost :: unique_lock上尝试try_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. 现在我想使用unique_lock(也是一个作用域的互斥锁)而不是普通的boost :: mutex。 I want this to avoid all the unlock() calls from the function body. 我希望这可以避免来自函数体的所有unlock()调用。

You can either defer the locking with the Defer constructor , or use the the Try constructor when creating your unique_lock : 您可以使用Defer构造函数推迟锁定,也可以在创建unique_lock时使用Try构造 unique_lock

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

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

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

Previous answers may be outdated. 以前的答案可能已经过时。 I'm using boost 1.53 and this seems to work: 我正在使用boost 1.53,这似乎有效:

boost::unique_lock<boost::mutex> lk(myMutex, boost::try_to_lock);
if (lk)
  doTheJob();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM