FrozenHeart FrozenHeart - 2 months ago 27
C++ Question

Recursive lock() call in g++

Why does the following code result in a deadlock in g++ 5.4.0?

#include <mutex>

int main()
{
std::mutex m;
m.lock();
m.lock();
}


As far as I know, this code should result in an exception according to the Standard:


30.4.1.2 Mutex types [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
.


What's wrong then? Is it a bug in the library?

Answer

Your code has undefined behaviour, because you are violating a precondition ([thread.mutex.requirements.mutex]):

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

Requires: If m is of type std::mutex [...], the calling thread does not own the mutex.

Comments