On a POSIX system, std::mutex
will probably be implemented using POSIX mutexes, and std::mutex::lock()
will eventually delegate to pthread_mutex_lock()
. Although C++ mutexes are not required to be implemented using POSIX mutexes, the authors of the C++ standard multi-threading seem to have modelled the possible error conditions on the POSIX error conditions, so examining those can be instructive. As user hmjd says, the C++ error conditions permitted for the lock
method are operation_not_permitted
, resource_deadlock_would_occur
and device_or_resource_busy
.
The POSIX error conditions are:
EINVAL
: if a POSIX specific lock-priorty feature is misused, which can never happen if you use only the standard C++ multi-threading facilities. This case might correspond to the operation_not_permitted
C++ error code.
EINVAL
: if the mutex has not been initialized, which would correspond to a corrupted std::mutex
object, use of a dangling reference, or some other undefined behaviour that indicates a program bug.
EAGAIN
: if the mutex is recursive and the recursion is too deep. That can't happen to a std::mutex
, but could happen for a std::recursive_mutex
. This would seem to correspond to the device_or_resource_busy
error condition.
EDEADLK
: if deadlock would occur because of the thread already holds the lock. This would correspond to the resource_deadlock_would_occur
C++ error code, but would indicate a program bug, because a program should not attempt to lock a std::mutex
it already holds a lock on (use a std::recursive_mutex
if you really want to do that).
The C++ operation_not_permitted
error code is evidently intended to correspond to the POSIX EPERM
error status. The pthread_mutex_lock()
function never gives this status code. But the POSIX manual page that describes that function also describes the pthread_mutex_unlock()
function, which may given EPERM
if you try to unlock a lock you have not locked. Perhaps the C++ standards authors included operation_not_permitted
by a mistaken reading of the POSIX manual page. As C++ has no concept of lock "permissions", it is hard to see how any correctly constructed and manipulated lock (used in accordance with the C++ standard, without invoking any undefined behaviour) could result in EPERM
and thus operation_not_permitted
.
device_or_resource_busy
is not permitted from C++17, which suggests it never really happens in practice, and its inclusion for C++11 was an error.
To summarize, the only cases in which std::mutex::lock()
could throw an exception indicate program bugs. So it can be reasonable to assume the method "never" throws an exception.