How to execute a piece of code only once?(如何只执行一段代码一次?)
问题描述
我有一个应用程序,其中包含多个功能.每个函数都可以根据用户输入多次调用.但是,我只需要在一个函数中执行一小段代码,最初是在应用程序启动时.当稍后再次调用相同的函数时,不得执行这段特定的代码.代码在 VC++ 中.请告诉我处理这个问题的最有效方法.
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.
推荐答案
使用具有构造函数的全局静态对象(在 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_once 或 constructor 函数 __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 上可用!
这篇关于如何只执行一段代码一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何只执行一段代码一次?
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
