Reputation: 20756
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
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
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 typestd::mutex
[...], the calling thread does not own the mutex.
Upvotes: 5