简体   繁体   English

为什么将 std::mutex 锁定两次“未定义行为”?

[英]Why is locking a std::mutex twice 'Undefined Behaviour'?

As per this article :根据这篇文章

If you try and lock a non-recursive mutex twice from the same thread without unlocking in between, you get undefined behavior.如果您尝试从同一线程锁定非递归互斥锁两次,中间没有解锁,则会出现未定义的行为。

My very naive mind tells me why don't they just return an error?我非常天真的头脑告诉我他们为什么不直接返回错误? Is there a reason why this has to be UB?这有什么理由必须是UB吗?

Because it never happens in a correct program, and making a check for something that never happens is wasteful (and to make that check it needs to store the owning thread ID, which is also wasteful).因为它永远不会在正确的程序中发生,并且对永远不会发生的事情进行检查是浪费的(并且要进行检查需要存储拥有线程的 ID,这也是浪费)。

Note that it being undefined allows debug implementations to throw an exception, for example, while still allowing release implementations to be as efficient as possible.请注意,未定义它允许调试实现抛出异常,例如,同时仍然允许发布实现尽可能高效。

Undefined behavior allows implementations to do whatever is fastest/most convenient.未定义的行为允许实现做任何最快/最方便的事情。 For example, an efficient implementation of a non-recursive mutex might be a single bit where the lock operation is implemented with an atomic compare-and-swap instruction in a loop.例如,非递归互斥体的有效实现可能是单个位,其中锁定操作是通过循环中的原子比较和交换指令实现的。 If the thread that owns the mutex tries to lock it again it will deadlock because it is waiting for the mutex to unlock but since nobody else can unlock it (unless there's some other bug where some thread that doesn't own it unlocks it) the thread will wait forever.如果拥有互斥锁的线程试图再次锁定它,它将死锁,因为它正在等待互斥锁解锁,但因为没有其他人可以解锁它(除非存在其他一些不拥有它的线程解锁它的错误)线程将永远等待。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM