Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a piece of code only once?

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.

like image 673
Darzen Avatar asked Dec 07 '11 08:12

Darzen


People also ask

How do you make code run only 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. Make sure to initialize that bool to false! static bool initialized(false); otherwise you never know what'll be in memory once allocated.


2 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.

like image 124
Bediver Avatar answered Sep 29 '22 18:09

Bediver


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 */ } );     .... } 
like image 20
Soren Avatar answered Sep 29 '22 18:09

Soren