c++ - std::lock_guard() 用于锁定的 std::mutex

标签 c++ multithreading c++11

我是 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/

相关文章:

c++ - 私有(private)继承 : name lookup error

java - 为什么我的 Java 应用程序不在每次循环时播放声音?

java - 调用 Web 服务的线程 - 如何控制线程状态?

C++ : Check if the template type is one of the variadic template types

c++ - 为什么bernoulli_distribution::param_type 的构造函数是显式的?

c++ - 如何在现代 C++ 中基于另一组可变参数模板参数来表示可变参数模板类型?

c++ - 使用基类指针调用函数?

c++ - Eclipse:函数 'to_string' 无法解析

C++ 使用线程作为定时器

.net - Semaphore.WaitOne/Release vs Monitor.Pulse/Wait