Should the mutex operation throw a system_error for locking twice?

3.6k Views Asked by At

Here is the code

mutex mtx;
try{
    mtx.lock();
    mtx.lock();
}catch(system_error& e){
    mtx.unlock();
    cout << e.what() << '\n';
    cout << e.code() << '\n';
}

An output device or resource busy, generic: 16 is expected but never seen.

gcc version 4.8.4

p.s.

Code above is from Bjarne Stroustrup's book -- the C++ programming language, 42.3.1.2 mutex Error. According to the book, a system_error should appear. That question about the "undefined behaviour" is posted in 2012, even before the publication of the book.

1

There are 1 best solutions below

0
user5309912 On

This is undefined behavior. If we look at [mutex.requirements.mutex], it has a prerequisite that the calling thread does not own the mutex, and a postcondition that the calling thread does own the mutex. device_or_resource_busy pertains to when ANOTHER calling thread tries to lock the mutex. However, it's implementation-defined whether or not resource_deadlock_would_occur is thrown.

This question is a duplicate of Why is locking a std::mutex twice 'Undefined Behaviour'?