我是 C++11 线程的新手。
下面这段代码只能由第一个线程执行。
其他线程(可能与第一个线程竞争)不应进入锁定代码区域(这就是 std::try_lock()
存在的原因)。
std::mutex mu;
// now ensure this will get called only once per event
if (std::try_lock(mu) != -1)
{
return;
}
{
std::lock_guard<std::mutex> guard(mu);
// critical section
} // mutex will be unlocked here
(除了编写我自己的 lock_guard 之外)有没有一种方法可以使用类似的标准 std::lock_guard
变体,但是这会占用我的 !locked! mutex(上面 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
)。
关于c++ - std::lock_guard() 用于锁定的 std::mutex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25033453/