gpt4 book ai didi

c++ - 为什么在死锁的情况下 lock() 不抛出异常

转载 作者:行者123 更新时间:2023-11-30 01:09:49 24 4
gpt4 key购买 nike

假设我们有以下代码:

#include <mutex>
#include <thread>

std::mutex m;

void foo()
{
m.lock();
}

int main()
{
std::thread th(foo);
m.lock();
th.join();
}

我知道这段代码包含死锁,但我想知道 C++ 标准中的以下语句:

30.4.1.2 互斥量类型 [thread.mutex.requirements.mutex]

6 The expression m.lock() shall be well-formed and have the following semantics:

[...]

12 Throws: system_error when an exception is required (30.2.2).

13 Error conditions:

— (13.1) operation_not_permitted — if the thread does not have the privilege to perform the operation.

— (13.2) resource_deadlock_would_occur — if the implementation detects that a deadlock would occur.

— (13.3) device_or_resource_busy — if the mutex is already locked and blocking is not possible.

正如我们所见,违反这些规则之一应该会导致异常:

30.2.2 异常[thread.req.exception]

1 Some functions described in this Clause are specified to throw exceptions of type system_error (19.5.7). Such exceptions shall be thrown if any of the function’s error conditions is detected or a call to an operating system or other underlying API results in an error that prevents the library function from meeting its specifications

我提供的代码肯定包含死锁。那么标准库是否应该在这种情况下抛出异常(因为 g++ 和 Visual C++ 不这样做)?如果不是,为什么?因为从我的角度来看,它似乎属于 13.2 (resource_deadlock_would_occur) 或 13.3 (device_or_resource_busy) 类别。

最佳答案

您应该编写代码来处理死锁异常,但不要依赖它们来解决死锁。无法保证会抛出死锁异常,因为无法保证检测到它们。换句话说,实现不必检测死锁,它可以检测死锁,这就是发现死锁时的处理方式。这并不意味着他们会被发现。

死锁代码是逻辑错误,不要写会死锁的代码。

关于c++ - 为什么在死锁的情况下 lock() 不抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39355788/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com