c++ - 使用 std::try_to_lock 的意外行为

标签 c++ multithreading c++11 locking mutex

当我尝试运行以下代码时,我遇到了令人惊讶和冲突的行为。

#include <iostream>
#include <mutex>

int main() {
    std::mutex mtx;
    std::unique_lock<std::mutex> lock1(mtx);
    std::unique_lock<std::mutex> lock2(mtx, std::try_to_lock);

    std::cout << "lock1 owns lock: " << lock1.owns_lock() << std::endl;
    std::cout << "lock2 owns lock: " << lock2.owns_lock() << std::endl;
}

当我在我的计算机上运行它时(使用 clang++ 4.0.1 或 g++ 7.3.0 的 linux)它打印出 lock1lock2 拥有锁(奇怪)。当我在 cpp.sh 上运行它时,它说 lock1 拥有锁,但 lock2 不拥有锁(如我所料)。

所有都使用 C++11 和 -Wall 没有优化。

最佳答案

documentation 中所述对于 std::unique_lock 构造函数:

  1. Tries to lock the associated mutex without blocking by calling m.try_lock(). The behavior is undefined if the current thread already owns the mutex except when the mutex is recursive.

重点是我的。因为 std::mutex 不是递归的,所以你有未定义的行为 - std::mutex::try_lock()

If try_lock is called by a thread that already owns the mutex, the behavior is undefined.

关于c++ - 使用 std::try_to_lock 的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51877755/

相关文章:

c++ - 如何在 cpp 中打印小数点后的特定位数?

c# - 异步函数进行异步调用

java - 如何暂停 main()

multithreading - 线程在使用 MSTEST 和 Selenium 的并行 Web 测试中中止

c++ - 抛出的异常 : read access violation. **node** 是 0xDDDDDDDD。发生

C++11 多线程 : Valgrind uninitialized value(s) warning

c++ - 使用显式命名空间限定符时,模板实例化行为会发生变化吗?

c++ - std::unordered_set::equal_range 迭代器问题

c++ - 如何为静态模板方法起别名?

c++ - 函数返回一个由 vector ​​组成的元组