如何只执行一段代码? [英] How to execute a piece of code only once?
问题描述
我有一个应用程序,它有几个功能。根据用户输入可以多次调用每个功能。但是,我只需要在应用程序启动时执行一次函数中的一小段代码。当在稍后的时间再次调用这个相同的函数时,这段代码不能被执行。代码位于 VC ++ 中。请告诉我处理这种情况的最有效的方法。
在构造函数中使用全局静态对象$ C>主)?或者只是在一个例程中
static bool initialized;
if(!initialized){
initialized = true;
//执行初始化部分
}
这还不够快!
addenda
在多线程这可能是不够的:
您可能也对 pthread_once 或 功能 __属性__
GCC 。
使用C ++ 11,您可能需要 std :: call_once 。
您可能需要使用 < atomic>
并且可能会声明 static volatile std :: atomic_bool initialized;
(但你编辑小心)如果你的函数可以从多个线程中调用。
但是这些可能不适用于你的系统。它们在Linux上可用!
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.
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!
这篇关于如何只执行一段代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!