Why does unlocking a mutex which is already kept locked by another thread cause undefined behavior?
According to http://www.cplusplus.com/reference/mutex/mutex/unlock/ , if, say, thread 1 locks a mutex, and thread 2 then tries to unlock the same mutex before it is unlocked, we incur in undefined behavior.
The link you provided actually talks about double unlocking, not double locking. However, the operation (i.e. unlocking the mutex from other thread, while owner thread is not locking it) is UB because the language does not define how a mutex lock should be implemented, thus (and this is pure conjecture) enabling a binary lock, which double unlock might actually lock...
Looking at this documentation on the member function unlock(), which is the member function whose documentation you are linking:
https://en.cppreference.com/w/cpp/thread/mutex/unlock
It states:
std::mutex::unlock()
Unlocks the mutex.
The mutex must be locked by the current thread of execution, otherwise, the behavior is undefined.
So I think the documentation simply states that if a thread tries to unlock a mutex it does not own, we incur in undefined behavior.
For what concerns the title of the question: locking a lock owned by another thread is a well defined behavior (it is why we have std::mutex) https://en.cppreference.com/w/cpp/thread/mutex/lock:
std::mutex::lock()
Locks the mutex. If another thread has already locked the mutex, a call to lock will block execution until the lock is acquired.
As a side note, directly unlocking a mutex is usually a bad idea, you should use RAII wrappers like std::lock_guard
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With