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

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 上可用!

这篇关于如何只执行一段代码一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何只执行一段代码一次?

基础教程推荐