I have an application which has several functions in it. Each function can be called many times based on user input. However I need to execute a small segment of the code within a function only once, initially when the application is launched. When this same function is called again at a later point of time, this particular piece of code must not be executed. The code is in VC++. Please tell me the most efficient way of handling this.
9 Answers
Compact version using lambda function:
void foo()
{
static bool once = [](){
cout << "once" << endl;
return true;
} ();
cout << "foo" << endl;
}
Code within lambda function is executed only once, when the static variable is initialized to the return value of lambda function. It should be thread-safe as long as your compiler support thread-safe static initialization.
-
1Excellent, I was thinking that the compiler already does that when initializing a static and thus we should be able to benefit from that and here is the right answer (instead of using a flag or
run_once()
) Oct 11, 2016 at 4:29 -
@Bediver if you store that lambda inside an auto variable instead of executing it immediately, it will be able to be called more than once. Or is that UB?– KeyC0deOct 3, 2018 at 18:21
-
2This will show a warning 'warning: unused variable 'once' [-Wunused-variable]'. With C++17 you could use [[maybe_unused]] to suppress it.– techolicApr 2, 2019 at 5:06
-
2If you compare the assembly code generated by this with that when you use std::call_once then this code looks a LOT better! godbolt.org/z/s3YPeb Feb 8, 2021 at 6:59
Using C++11 -- use the std::call_once
#include <mutex>
std::once_flag onceFlag;
{
....
std::call_once ( onceFlag, [ ]{ /* my code body here runs only once */ } );
....
}
-
I didn't know about this API, thanks. A couple of things: Firstly make sure onceFlag has global scope. It can't have thread or function scope. Secondly, I don't see a way to easily compact this down to a single expression. (Not a huge deal compared to having a clear, standard API.) Jun 27, 2014 at 16:16
-
3I am using this to great affect, the only thing I would do to improve upon it is if you declare your once_flag inside the function as a static, it will only be initialized once and your code inside call_once will only run once, but you can keep all the code in the same scope. Jan 12, 2016 at 23:43
-
You can read more about the usage here: en.cppreference.com/w/cpp/thread/call_once Feb 18, 2022 at 6:50
Use global static objects with constructors (which are called before main
)? Or just inside a routine
static bool initialized;
if (!initialized) {
initialized = true;
// do the initialization part
}
There are very few cases when this is not fast enough!
addenda
In multithreaded context this might not be enough:
You may also be interested in pthread_once or constructor
function __attribute__
of GCC.
With C++11, you may want std::call_once.
You may want to use <atomic>
and perhaps declare static volatile std::atomic_bool initialized;
(but you need to be careful) if your function can be called from several threads.
But these might not be available on your system; they are available on Linux!
-
1That was my thought too, but then reading @KirilKirov's comment I had to bang my head against some stonework. Cheers, Dec 7, 2011 at 9:05
-
3This won't work as is in a multithreaded setting but should good for most use cases– KatOct 17, 2013 at 18:27
-
1Make sure to initialize that bool to false!
static bool initialized(false);
otherwise you never know what'll be in memory once allocated.– thayneJun 5, 2017 at 20:10 -
2AFAIK, a
static
variable is initialized to all-zero bits, which isfalse
for abool
Jun 6, 2017 at 0:17 -
2This is thread-safe as of C++11. And yes, static variables are zero-initialised. However, I still think it's good to be in the habit of always explicitly initialising primitive types; that way, you won't run into horror later if it's refactored to not be implicitly initialised. Jan 8, 2020 at 10:38
You can use local static variable:
void foo()
{
static bool wasExecuted = false;
if (wasExecuted)
return;
wasExecuted = true;
...
}
Additionally to @Basile's answer, you can use a lambda to encapsulate the static variable as follows:
if ([] {
static bool is_first_time = true;
auto was_first_time = is_first_time;
is_first_time = false;
return was_first_time; } ())
{
// do the initialization part
}
This makes it easy to convert into a general-purpose macro:
#define FIRST_TIME_HERE ([] { \
static bool is_first_time = true; \
auto was_first_time = is_first_time; \
is_first_time = false; \
return was_first_time; } ())
Which can be placed anywhere you want call-by-need:
if (FIRST_TIME_HERE) {
// do the initialization part
}
And for good measure, atomics shorten the expression and make it thread-safe:
#include <atomic>
#define FIRST_TIME_HERE ([] { \
static std::atomic<bool> first_time(true); \
return first_time.exchange(false); } ())
could you do this
have a function that return a bool or some datatype called init
I made it happen this way, you need static bool to make it happens
bool init()
{
cout << "Once " <<endl;
return true||false;// value isn't matter
}
void functionCall()
{
static bool somebool = init(); // this line get executed once
cout << "process " <<endl;
}
int main(int argc, char *argv[])
{
functionCall();
functionCall();
functionCall();
return EXIT_SUCCESS;
}
for C
#include <stdio.h>
void init()
{
printf("init\n");
}
void process()
{
static int someint = 0;
if(someint == 0)
{
someint = 1;
init();
}
printf("process\n");
}
int main()
{
process();
process();
process();
return 0;
}
-
Is it executed once because "static will be initialised only once" ??– MakeshApr 27, 2016 at 12:25
std::call_once()
et al. may be overkill if you don't need a totally thread-safe solution.
If not, we can make this look especially elegant when using C++17's initialisation-within-if
and std::exchange()
:
#include <utility>
void
do_something_expensive_once()
{
if ( static auto called = false; !std::exchange(called, true) ) {
do_something_expensive();
}
}
If this is a pattern you use a lot, then we can encapsulate it via a tag type:
#include <iostream>
#include <utility>
template <typename T>
auto
call_once()
{
static auto called = false;
return !std::exchange(called, true);
}
void
do_something_expensive()
{
std::cout << "something expensive\n";
}
void
do_something_expensive_once()
{
if ( call_once<struct TagForSomethingExpensive>() ) {
do_something_expensive();
}
}
auto
main() -> int
{
for (auto i = 0; i < 5; ++i) {
do_something_expensive_once();
}
return 0;
}
This will only print something expensive
a single time. Result! It also uses the ability to declare a tag struct
in a template argument list, for maximal brevity.
Alternatively, you could template on a function's address, a unique integer, etc.
You can then also pass a callable to call_once()
, and so on, and so forth. As usual for C++: the possibilities are endless!
-
The downvoter is welcome to enlighten me, now that I fixed a simple typo, which was the only thing I can see wrong here. Apr 24, 2020 at 8:40
-
I am not the downvoter but your code is incorrect. Yes
static auto called
is initialized tofalse
in a thread safe way. But then concurrent calls tostd::exchange
are not guaranteed to be serialized. Thus you may calldo_something_expensive
more than once.– igor.solMay 25, 2021 at 8:25 -
OP didn't specify that a thread-safe solution was needed, and this is fine if not. That doesn't mean 'my code is incorrect'; it only means it might not be sufficient for everyone depending on their precise scenario... I've edited to clarify anyway. May 25, 2021 at 11:27
-
Well, if this is not thread safe solution then I would not use std::exchange:
if ( static auto called = false; !called ) { do_something_expensive();called = true; }
– igor.solMay 25, 2021 at 12:55 -
and does that matter at all, beyond personal stylistic preference? I prefer it the way it is. May 25, 2021 at 13:15
With due respect to std::call_once()
and the usual caveats about thread safety, here's another lightweight option which avoids unused variable warnings and keeps our flag in block scope:
for (static bool once=true; once; once=false) {
yourCodeHere();
}
do {
//execute code once
} while (false)
-
While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Jun 22, 2020 at 22:24
-
This does not answer the question that was asked. Adding the pointless
do
/while
does nothing, and it certainly doesn't ensure the code within is only executed once, on the first call to the containing function. Nov 19, 2020 at 13:52 -
Do you mind explaining how it does nothing how it doesn't execute only once? The do part executes, then while is false so the do will not execute again. Unless you call the parent function multiple times, then yes, the do section will execute many times. Nov 24, 2020 at 14:57
-
It doesn't answer the actual Q: "Each function can be called many times based on user input. However I need to execute a small segment of the code within a function only once, initially when the application is launched." That means the function can be called more than once, but part of it must know if it is the first call & only execute if so. Your
do
/while
adds nothing, especially not to make calls after 1st not run code. You answered 'how do I make N lines of code only run once', which isn't a real Q as the answer is just 'write them once'... to which a fake loop adds precisely zero. Dec 16, 2020 at 9:57 -
1this is just a loop with a single iteration, its essentially exactly the same as
// execute code once
without the loop Mar 3, 2021 at 12:25
main
? Or before the main loop of the program?