c++ - 为什么锁定 std::mutex 不会阻塞线程

标签 c++ c++11 concurrency

我写了下面的代码来测试我对std::mutex的理解

int main() {
    mutex m;
    m.lock();
    m.lock(); // expect to block the thread
}

然后我得到一个system_error: device or resource busy。第二个 m.lock() 不是应该阻塞线程吗?

最佳答案

来自 std::mutex :

A calling thread must not own the mutex prior to calling lock or try_lock.

来自std::mutex::lock :

If lock is called by a thread that already owns the mutex, the program may deadlock. Alternatively, if an implementation can detect the deadlock, a resource_deadlock_would_occur error condition may be observed.

异常(exception)条款:

Throws std::system_error when errors occur, including errors from the underlying operating system that would prevent lock from meeting its specifications. The mutex is not locked in the case of any exception being thrown.

因此它不应该阻塞线程。在您的平台上,实现似乎能够检测线程何时已经是锁的所有者并引发异常。如描述中所示,这可能不会发生在其他平台上。

关于c++ - 为什么锁定 std::mutex 不会阻塞线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16664375/

相关文章:

c++ - 单元测试、认可测试和数据文件

c++ - 返回转发引用参数 - 最佳实践

c++ - 用右值初始化左值引用

concurrency - 同时处理一个 channel 会导致意外的输出

c# - CPU使用率未最大化,并且依赖异步/等待的服务器应用程序中的高度同步

c++ - 预编译 header 是否可以比干净构建的经典包含慢?

c++ - text_multifile_backend 如何设置 rool 文件大小

c++ - 使用 GDI+ 的图层

c++使用模板制作最通用的函数

java - CompletableFuture 如何知道任务是独立的?