C++ Logo

std-proposals

Advanced search

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

From: Giuseppe D'Angelo <giuseppe.dangelo_at_[hidden]>
Date: Thu, 9 May 2024 07:51:29 +0200
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.


My 2 c,

--
Giuseppe D'Angelo

Received on 2024-05-09 05:51:35