FrozenHeart
FrozenHeart

Reputation: 20756

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?

Upvotes: 2

Views: 149

Answers (2)

Bo Persson
Bo Persson

Reputation: 92311

That exception was removed from std::mutex by Library Issue #2309, so perhaps g++ 5.4 is just up-to-date.

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 477368

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.

Upvotes: 5

Related Questions