简体   繁体   中英

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. For the moment, I only document it by a \\attention in Doxygen, but I would like to add an assertion.

My question : Is there a elegant way to know that the main function is not running yet ?

Example (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.

If static std::atomic<bool> s; is defined, along with a little toggling 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); 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. Using std::atomic is probably overkill given that the behaviour of main calling itself is undefined in C++. If you don't have C++11, then volatile bool is adequate: effectively your not in main until that extra statement has completed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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