Date: Sun, 27 Oct 2024 16:57:31 +0000
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".
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".
Received on 2024-10-27 16:57:40