Can std :: mutex :: lock throw event if everything looks “good”?

It is not explicitly stated from CPPReference that the lock function std::mutex will not throw if the lock won’t lead to a dead lock.

PThread lock only has a deadlock error. I do not know to implement a streaming stream. I also don't know if they are other thread implementations used as backend std::thread / std::mutex .

So my question is: "Do I have to write my code as if, sometimes, for no particular reason, the lock could fail?".

I really need to block the mutex in some noexcept methods, and I want to make sure that they are no exception.

+4
source share
2 answers

The member function std::mutex::lock() not declared as noexcept from section 30.4.1.2. Mutex types of C ++ 11 standard (draft n3337), clause 6:

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

  • ...
  • Throws: system_error when an exception is required (30.2.2).
  • Error conditions:
    • operation_not_permitted - if the thread does not have privileges to perform the operation.
    • resource_deadlock_would_occur - if the implementation detects that a deadlock will occur.
    • device_or_resource_busy - if the mutex is already locked and blocking is not possible.

This means that any function using mutex::lock() cannot be marked with noexcept , unless that function is able to handle the exception itself and prevents it from pushing the caller.


I cannot comment on the likelihood of these error conditions occurring, but with respect to std::mutex and resource_deadlock_would_occur (which can be selected), this indicates an error in the code, and not at runtime, since this error can be raised if the thread tries to block std::mutex , which it already has. From Section 30.4.1.2.1 of the Mutex Class, Section 4:

[Note. A program can become deadlocked if the thread that owns the mutex object calls lock () on that object. If the implementation can detect a deadlock, the resource_deadlock_would_occur error condition may be observed. -end note]

By choosing std::mutex as the type of lock, the programmer explicitly states that trying the same thread to block mutex , which is already locked, is not possible. If this is a legitimate execution path for a thread to lock a mutex , then a more appropriate choice is std:recursive_mutex (but switching to recursive_lock does not mean that the lock() function is an exception).

+7
source

It is safe to assume that the mutex will not be thrown if you can guarantee that none of the error conditions (as indicated in the hmjd answer) is present. How to put this call into the noexcept function depends on how you want to deal with the (rather impossible) failure. If the default value is noexcept (for calling std::terminate , you don’t need to do anything. If you want to make the log impossible error, wrap the function in a try / catch clause.

+1
source

Source: https://habr.com/ru/post/1490505/


All Articles