简体   繁体   English

如何知道 main() 是否正在运行?

[英]How to know if the main() is running?

Context : In my application, I have some functions using global variables.上下文:在我的应用程序中,我有一些使用全局变量的函数。 Due to the undefined order of allocation of the global variables, I want to forbid the call to these functions before the main function is running.由于全局变量的分配顺序未定义,我想在main函数运行之前禁止对这些函数的调用。 For the moment, I only document it by a \\attention in Doxygen, but I would like to add an assertion.目前,我只通过 Doxygen 中的\\attention来记录它,但我想添加一个断言。

My question : Is there a elegant way to know that the main function is not running yet ?我的问题:有没有一种优雅的方法可以知道main函数还没有运行?

Example (uniqid.cpp):示例(uniqid.cpp):

#include <boost/thread.hpp>
#include <cassert>
unsigned long int uid = 0;
boost::mutex uniqid_mutex;
unsigned long int uniquid()
{
  assert(main_is_running() && "Forbidden call before main is running");
  boost::mutex::scoped_lock lock(uniqid_mutex);
  return ++uid;
}

My first (ugly) idea : My first idea to do that is by checking another global variable with a specific value.我的第一个(丑陋)想法:我的第一个想法是检查另一个具有特定值的全局变量。 Then the probability to have this value in the variable before initialisation is very small :那么在初始化之前变量中有这个值的概率非常小:

// File main_is_running.h
void launch_main();
bool main_is_running();

// File main_is_running.cpp
unsigned long int main_is_running_check_value = 0;
void launch_main()
{
  main_is_running_check_value = 135798642;
}
bool main_is_running()
{
  return (main_is_running_check_value == 135798642);
}

// File main.cpp
#include "main_is_running.h"
int main()
{
  launch_main();
  // ...
  return 0;
}

Is there a better way to do that ?有没有更好的方法来做到这一点?

Note that I can't use C++11 because I have to be compatible with gcc 4.1.2.请注意,我不能使用 C++11,因为我必须与 gcc 4.1.2 兼容。

If static std::atomic<bool> s;如果static std::atomic<bool> s; is defined, along with a little toggling struct :被定义,以及一个小的切换struct

struct toggle
{
    toggle(std::atomic<bool>& b) : m_b(b)
    {
        m_b = true;
    }   
    ~toggle()
    {
        m_b = false;
    }
    std::atomic<bool>& m_b;
};

Then, in main , write toggle t(s);然后,在main ,写toggle t(s); as the first statement.作为第一个声明。 This is one of those instances where having a reference as a member variable is a good idea.这是将引用作为成员变量是一个好主意的实例之一。

s can then tell you if you're in main or not.然后s可以告诉您是否在main Using std::atomic is probably overkill given that the behaviour of main calling itself is undefined in C++.考虑到main调用本身的行为在 C++ 中未定义,使用std::atomic可能有点矫枉过正。 If you don't have C++11, then volatile bool is adequate: effectively your not in main until that extra statement has completed.如果您没有 C++11,那么volatile bool就足够了:实际上,在该额外语句完成之前,您不在main

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM