当我尝试运行以下代码时,我遇到了令人惊讶和冲突的行为。
#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)它打印出 lock1
和 lock2
拥有锁(奇怪)。当我在 cpp.sh
上运行它时,它说 lock1
拥有锁,但 lock2
不拥有锁(如我所料)。
所有都使用 C++11 和 -Wall
没有优化。
最佳答案
如 documentation 中所述对于 std::unique_lock
构造函数:
- 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/