How to execute a piece of code only once?

后端 未结 8 851
隐瞒了意图╮
隐瞒了意图╮ 2020-12-01 04:35

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 wi

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-01 05:09

    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 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!

提交回复
热议问题