[英]How to know if the main() is running?
上下文:在我的應用程序中,我有一些使用全局變量的函數。 由於全局變量的分配順序未定義,我想在main
函數運行之前禁止對這些函數的調用。 目前,我只通過 Doxygen 中的\\attention
來記錄它,但我想添加一個斷言。
我的問題:有沒有一種優雅的方法可以知道main
函數還沒有運行?
示例(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;
}
我的第一個(丑陋)想法:我的第一個想法是檢查另一個具有特定值的全局變量。 那么在初始化之前變量中有這個值的概率非常小:
// 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;
}
有沒有更好的方法來做到這一點?
請注意,我不能使用 C++11,因為我必須與 gcc 4.1.2 兼容。
如果static std::atomic<bool> s;
被定義,以及一個小的切換struct
:
struct toggle
{
toggle(std::atomic<bool>& b) : m_b(b)
{
m_b = true;
}
~toggle()
{
m_b = false;
}
std::atomic<bool>& m_b;
};
然后,在main
,寫toggle t(s);
作為第一個聲明。 這是將引用作為成員變量是一個好主意的實例之一。
然后s
可以告訴您是否在main
。 考慮到main
調用本身的行為在 C++ 中未定義,使用std::atomic
可能有點矯枉過正。 如果您沒有 C++11,那么volatile bool
就足夠了:實際上,在該額外語句完成之前,您不在main
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.