2

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.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
Milo Lu
  • 3,176
  • 3
  • 35
  • 46
  • Why do you expect `system_error` to be thrown? – juanchopanza Sep 07 '15 at 16:53
  • [Don't see anything in here about throwing exceptions.](http://en.cppreference.com/w/cpp/thread/mutex) – user4581301 Sep 07 '15 at 16:58
  • 4
    "If lock is called by a thread that already owns the mutex, the behavior is undefined: the program *may* deadlock, or, if the implementation can detect the deadlock, a resource_deadlock_would_occur error condition may be thrown." – melak47 Sep 07 '15 at 17:04

1 Answers1

3

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'?