![](/img/trans.png)
[英]Is there a shorthand for std::lock_guard<std::mutex> lock(m)?
[英]std::lock_guard() for a locked std::mutex
我是C ++ 11线程的新手。
以下代码只能由第一个线程执行。
其他线程(可能与第一个线程竞争)不应该进入锁定的代码区域(这就是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
(在编写我自己的lock_guard之外)有没有办法使用类似的标准std::lock_guard
变体,但是我的锁定会被锁定! 互斥(上面的std::try_lock()
效果)并且在调用该守卫的d-tor时简单地解锁它?
用这个:
// 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
更新并且不要使用以下划线开头的变量名(作为_mutex
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.