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

mar*_*.de 3 c++ multithreading c++11

我是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        
Run Code Online (Sandbox Code Playgroud)

(在写我自己的lock_guard以外)有没有办法使用类似的标准std::lock_guard变体,但这将使我的!锁定!互斥(std::try_lock()上面的效果)并且当调用该守卫的d-tor时简单地将其解锁?

vla*_*don 6

用这个:

// 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
Run Code Online (Sandbox Code Playgroud)

更新并且不要使用以下划线(as _mutex)开头的变量名称.


Cof*_*ode 2

看看这个

和这个

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

  • 几乎是正确的。lock_guard 不接受 try_to_lock_t。然而,可以在操作代码中使用现有的 try_lock,然后使用 std::adopt_lock 构造一个 lock_guard 来告诉它互斥锁已经被锁定。 (5认同)