使用std :: try_to_lock的意外行为 [英] Unexpected behavior using std::try_to_lock
问题描述
当我尝试运行以下代码时,我得到令人惊讶且矛盾的行为.
I get surprising and conflicting behavior when I try to run the following code.
#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的计算机)运行此命令时,它会打印出lock1
和lock2
都拥有锁(令人惊讶).当我在cpp.sh
上运行它时,它说lock1
确实拥有,但是lock2
不拥有该锁(我所期望的).
When I run this on my computer (linux with either clang++ 4.0.1 or g++ 7.3.0) it prints out that both lock1
and lock2
own the lock (surprising). When I run this on cpp.sh
it says that lock1
does own, but lock2
does not own the lock (what I expected).
所有人都使用C ++ 11和-Wall
而没有进行优化.
All are using C++11 and -Wall
without optimizations.
推荐答案
As stated in documentation for std::unque_lock
constructor:
5)尝试通过调用m.try_lock()锁定相关联的互斥锁而不会阻塞. 如果当前线程已经拥有该互斥锁,则该行为是不确定的,除非该互斥锁是递归的.
5) 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
不是递归的,因此您拥有UB- std::mutex::try_lock()
emphasis is mine. Since std::mutex
is not recursive you have UB - std::mutex::try_lock()
如果try_lock由已经拥有互斥锁的线程调用,则行为未定义.
If try_lock is called by a thread that already owns the mutex, the behavior is undefined.
这篇关于使用std :: try_to_lock的意外行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!