已锁定的std::mutex使用std::lock_guard()。

6

我刚接触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变体可用,但它将获取我未加锁的mutex(即以上std::try_lock()的效果),并在该guard的析构函数被调用时简单地解锁它?

2个回答

12
请使用以下内容:
// 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++标识符中使用下划线的规则是什么? - user

2
请看这里:

点击此处

以及这里

从这些信息中可以看出,如果像这样指定第二个参数 std::lock_guard<std::mutex> guard(_mutex, std::try_to_lock),则行为将更改为类似于std::try_lock而不是std::lock

5
几乎正确。lock_guard不接受try_to_lock_t。但是可以在ops代码中使用现有的try_lock,然后使用std::adopt_lock构造一个lock_guard,告诉它互斥量已经被锁定。 - John5342

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接