C++ Logo

std-proposals

Advanced search

Re: [std-proposals] int Func(void) noreentry(-1)

From: David Brown <david_at_[hidden]>
Date: Fri, 3 Feb 2023 09:00:16 +0100
On 02/02/2023 12:59, Frederick Virchanza Gotham via Std-Proposals wrote:
> This week I had to fix a bug in a desktop GUI program. After doing
> some testing, I was leaning toward the possibility that one of the
> functions in the program was being re-entered (when it shouldn't be).

<snip>

>
> So I needed to protect this function from re-entry, not just by
> multiple threads but also by the same thread. It would be nice if
> there were a core-language feature for this, for example:
>
> int Func(void) noreentry(-1)
> {
> // The rest of the function goes here
> }
>


<snip>

>
> Mostly this feature would be used in desktop GUI programming, although
> someone might find another use for it. It would even be useful purely
> as a debugging tool.


This sounds to me like you have a bug in your code, not a case for a new
language feature. Either your code /should/ be calling the function in
a re-entrant manner, or it should not be. In the first case, you need
to make sure your function is safe for re-entrant use (perhaps by using
a mutex or recursive mutex, if that's what it takes). In the second
case, you have a program bug - an atomic flag might let you spot the
problem then print out debugging information.

So as I see it, "no_retry" would make more sense as an attribute. A
compiler could ignore it or optimise knowing that the function will
never (in correct code) be called recursively. And sanitizers or other
tools could check for failures of that assumption when you are doing
debugging.


The idea does sound a bit a "monitor" :

<https://en.wikipedia.org/wiki/Monitor_(synchronization)>

The key difference is that with monitors, you don't have an early return
when there is re-entrancy - the thread waits its turn politely. (That
also means you can't use it when re-calling the function within the same
thread.)

It might be interesting to consider adding a "monitor" keyword to C++
because it would give a very simple and clear way to achieve useful
locking. A monitor can sometimes be a bit heavy-handed, and be
unsuitable for high-performance code, but in many cases marking a class,
function or method as "monitor" would be a lot easier to get right than
manually defining mutexes and lock guards. It saves a lot of boilerplate.

Received on 2023-02-03 08:00:25