Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is locking a std::mutex twice 'Undefined Behaviour'?

As per this article:

If you try and lock a non-recursive mutex twice from the same thread without unlocking in between, you get undefined behavior.

My very naive mind tells me why don't they just return an error? Is there a reason why this has to be UB?

like image 512
Jesse Good Avatar asked Jun 23 '12 22:06

Jesse Good


People also ask

Can you lock mutex twice?

To solve your issue, you can use std::recursive_mutex , which can be locked/unlocked multiple times from the same thread.

What happens when mutex is locked?

Mutexes are used to protect shared resources. If the mutex is already locked by another thread, the thread waits for the mutex to become available. The thread that has locked a mutex becomes its current owner and remains the owner until the same thread has unlocked it.

Can multiple threads lock on a mutex?

The non-member function lock allows to lock more than one mutex object simultaneously, avoiding the potential deadlocks that can happen when multiple threads lock/unlock individual mutex objects in different orders.

What is the role of std :: mutex?

std::mutex The mutex class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads.


2 Answers

Because it never happens in a correct program, and making a check for something that never happens is wasteful (and to make that check it needs to store the owning thread ID, which is also wasteful).

Note that it being undefined allows debug implementations to throw an exception, for example, while still allowing release implementations to be as efficient as possible.

like image 106
R. Martinho Fernandes Avatar answered Oct 17 '22 12:10

R. Martinho Fernandes


Undefined behavior allows implementations to do whatever is fastest/most convenient. For example, an efficient implementation of a non-recursive mutex might be a single bit where the lock operation is implemented with an atomic compare-and-swap instruction in a loop. If the thread that owns the mutex tries to lock it again it will deadlock because it is waiting for the mutex to unlock but since nobody else can unlock it (unless there's some other bug where some thread that doesn't own it unlocks it) the thread will wait forever.

like image 16
Geoff Reedy Avatar answered Oct 17 '22 11:10

Geoff Reedy