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

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

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

然后我有一个system_error:设备或资源繁忙.不是第二个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.

和例外条款:

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.

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

翻译自:https://stackoverflow.com/questions/16664375/why-locking-a-stdmutex-dont-block-the-thread

转载注明原文:c – 为什么锁定std :: mutex不会阻塞线程