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.
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. Make sure to initialize that bool to false! static bool initialized(false); otherwise you never know what'll be in memory once allocated.
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.
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 */ } ); .... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With