Michele Piccolini
Michele Piccolini

Reputation: 2953

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.

Upvotes: 2

Views: 3767

Answers (3)

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

Upvotes: 1

phoenixstudio
phoenixstudio

Reputation: 2598

According to http://www.cplusplus.com/reference/mutex/mutex/unlock/:

All lock and unlock operations on the mutex follow a single total order, with all visible effects synchronized between the lock operations and previous unlock operations on the same object. If the mutex is not currently locked by the calling thread, it causes undefined behavior.

This simply means you should always (in the same thread) call lock before unlock.

Upvotes: 0

CIsForCookies
CIsForCookies

Reputation: 12817

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

Upvotes: 1

Related Questions