简体   繁体   English

std :: lock_guard()用于锁定的std :: mutex

[英]std::lock_guard() for a locked std::mutex

I am new to C++11 threading. 我是C ++ 11线程的新手。

The following piece of code should be executed only by the first thread. 以下代码只能由第一个线程执行。

The other threads (which might race with the first thread) should not enter the locked code area (that's why the std::try_lock() is there). 其他线程(可能与第一个线程竞争)不应该进入锁定的代码区域(这就是std::try_lock()存在的原因)。

std::mutex mutex;

// now ensure this will get called only once per event
if (std::try_lock(_mutex) != -1)
{ 
    return;
}

{
    std::lock_guard<std::mutex> guard(_mutex);
    // critical section

} // mutex will be unlocked here        

(Outside from writing my own lock_guard) Is there a way to use a similar & standard std::lock_guard variant, but which will take my !locked! (在编写我自己的lock_guard之外)有没有办法使用类似的标准std::lock_guard变体,但是我的锁定会被锁定! mutex (effect of std::try_lock() above) and simply unlock it when the d-tor of that guard will be called? 互斥(上面的std::try_lock()效果)并且在调用该守卫的d-tor时简单地解锁它?

Use this: 用这个:

// now ensure this will get called only once per event
if (_mutex.try_lock())
{ 
    std::lock_guard<std::mutex> guard(_mutex, std::adopt_lock);

    // critical section
} // mutex will be unlocked here

Update And don't use variable names starting with underscore (as _mutex ). 更新并且不要使用以下划线开头的变量名(作为_mutex )。

Have a look at this 看看这个

and this 和这个

From this info you can see that if you specify a second parameter like this std::lock_guard<std::mutex> guard(_mutex, std::try_to_lock) the behaviour is changed to act like std::try_lock rather than std::lock 从这个信息中你可以看到,如果你指定第二个参数,比如这个std::lock_guard<std::mutex> guard(_mutex, std::try_to_lock) ,行为就会改为像std::try_lock而不是std::lock

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

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