C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Opt out of multi-threading protection for static variables inside functions

From: Lénárd Szolnoki <cpp_at_[hidden]>
Date: Sun, 27 Oct 2024 19:16:09 +0000
It's possible to effectively opt-in. Have a static constinit optional, and do the initialisation dance yourself.


On 27 October 2024 16:57:31 GMT, Frederick Virchanza Gotham via Std-Proposals <std-proposals_at_[hidden]> wrote:
>Since C++11, we're guaranteed that a static variable defined inside a
>function will be protected behind the scenes by an "std::once_flag" to
>ensure that the variable only gets initialised once, and that
>concurrent threads will wait for the initialising thread to finish.
>
>Sometimes we don't want this, for example if:
>(1) The function will only ever be called by the same thread -- this
>is very common in GUI programs (i.e. only the GUI thread calls the
>function)
>(2) You have your own locks inside the function
>
>C++ has always been about efficiency -- not paying for things that you
>don't use. So how about we be able to opt out of the multi-threading
>protection?
>
>Either mark the function, or mark the variable, something like:
>
> void MyFunction(void) _SingleThreadOnly
> {
> static SomeClass obj("monkey");
> }
>
>or:
>
> void MyFunction(void)
> {
> static _SingleThreadOnly SomeClass obj("monkey");
> }
>
>Sometimes we write a function in C++, expecting it to only have one
>lock inside it (i.e. our own use of a 'mutex' or an 'atomic_flag'),
>but then we check the assembler and we see that there are actually two
>locks. We should be able to opt out of this unnecessary protection.
>
>Of course, this begs this question: What if the function is entered
>concurrently by another thread while the object is being initialised?
>One Possible Answer = "Undefined Behaviour".
>--
>Std-Proposals mailing list
>Std-Proposals_at_[hidden]
>https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2024-10-27 19:16:14