Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unlocking a mutex locked by another thread

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.

like image 373
Michele Piccolini Avatar asked Oct 23 '25 19:10

Michele Piccolini


2 Answers

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...

like image 162
CIsForCookies Avatar answered Oct 26 '25 10:10

CIsForCookies


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

like image 41
CuriouslyRecurringThoughts Avatar answered Oct 26 '25 09:10

CuriouslyRecurringThoughts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!