我写了下面的代码来测试我对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/