C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Proposal for extension std::mutex in ISO C++

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Thu, 9 May 2024 10:13:22 +0100
On Thu, 9 May 2024 at 06:52, Giuseppe D'Angelo via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> Hello,
>
> Il 09/05/24 06:44, anshul mittal via Std-Proposals ha scritto:
> > The std::mutex should not allow locking if the same thread is requesting
> > the lock on same mutex.
> >
> > You can get thread id using std::this_thread::get_id().
> >
> > Eg.
> > Current situation :
> > mutex mut;
> > mut.lock();
> > mut.lock();
> > This creates a deadlock.
> >
> > By putting thread id check the deadlock is prevented. I call this
> > SampleMutex.
> > SampleMutex mut;
> > mut.lock();
> > mut.lock(); // This lock should not happen and no deadlock created.
>
> There's multiple problems with this idea.
>
> 1) This goes against the general C++ principle of "don't pay for what
> you don't use". A program that doesn't lock the same mutex twice in the
> same thread doesn't need this facility. For such a program, checking the
> current thread id at every lock is just overhead.
>
> 2) All programs that are currently using mutex correctly (i.e.: all the
> existing *correct* programs) therefore don't need any of the sorts. The
> corollary is that such a feature is a pessimization for all existing
> code. That doesn't exactly sell the idea, to put it mildly.
>
> 3) If you need a recursive mutex, there's already a dedicated facility
> for that. But a recursive mutex seems to be different from what you're
> proposing: a recursive mutex requires the numbers of calls to lock() and
> unlock() to match, while yours doesn't.
>
> 4) Checking the thread id isn't sufficient, as this exposes you to ABA
> problems. A thread can lock the mutex and quit, and then the same id may
> get recycled by a new thread, which will then successfully lock the
> already locked mutex. That makes no sense.
>
> 5) If you just want a deadlock debugging feature for mutexes, then you
> can already build what you want around std::mutex. Or, just use TSAN
> and/or a mutex that offers this feature out of the box, like absl::Mutex.
>

6) It would be an ABI break, so would need much stronger motivation than
has been presented. The points above argue strongly we don't want this
change anyway, and we certainly don't want to break the ABI to get
something we don't want.

Received on 2024-05-09 09:14:41