且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何只执行一段代码一次?

更新时间:2022-03-25 00:12:52

使用具有构造函数的全局静态对象(在 main 之前调用)?或者只是在例行程序中

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!

在多线程上下文中,这可能还不够:

In multithreaded context this might not be enough:

您可能还对 pthread_onceconstructor 函数 __attribute__ GCC.

You may also be interested in pthread_once or constructor function __attribute__ of GCC.

对于 C++11,您可能需要 std::call_once.

With C++11, you may want std::call_once.

您可能想要使用 如果您的函数可以从多个线程调用,也许可以声明 static volatile std::atomic_bool 初始化;(但您需要小心).

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.

但是这些可能在您的系统上不可用;它们在 Linux 上可用!