我的目标是快速处理各种竞争条件,如果在大约同一时间在 2 个单独的线程中调用给定函数,这些竞争条件可能会导致问题。我的快速修复是通过在 main() 之前调用它们来保证函数已经初始化。这是我想出的解决方案,但我觉得我可能会重新发明轮子。 MSVC2010 STL 中是否有可用的选项? (还没有提升)或者是否有更好的方法来快速处理这些问题,而不必在这种情况下为每个函数添加重要的线程安全代码?
template <typename T, T func>
struct PreLoaderHelper
{
PreLoaderHelper()
{
wcout << L"Preload helper constructor" << endl;
func();
}
};
template <typename T, T func>
struct PreLoader
{
static PreLoaderHelper<T, func> _helper;
};
template <typename T, T func>
PreLoaderHelper<T, func> PreLoader<T, func>::_helper;
#define PRELOAD(fn) template struct PreLoader<decltype(&fn), fn>;
void foo() { wcout << L"inside foo" << endl; }
void bar() { wcout << L"inside bar" << endl; }
vector<wstring> & foobar()
{
static vector<wstring> sPresidents;
if(sPresidents.size() == 0)
{
sPresidents.push_back(L"George Washington");
sPresidents.push_back(L"John Addams");
sPresidents.push_back(L"Thomas Jefferson");
}
return sPresidents;
}
wstring foofoo(const wstring &) { wcout << L"inside foofoo" << endl; return L"foofoo";}
PRELOAD(foo);
PRELOAD(bar);
PRELOAD(foobar);
PRELOAD(foo);
int main()
{
return 0;
}
最佳答案
第一个问题:你真的必须先调用他们吗 进入主要?为什么不把它们称为主要的第一件事, 在开始任何线程之前?
否则:经典的习惯用法是在初始化器中使用它们 到一个静态变量。通常的方法是从一个 构造器;如果你有额外的数据必须是 初始化,这无疑是最好的方式。如果不, 像这样简单的东西:
static bool initialized = (function(), true);
会成功的。
形式上,这只保证它们将被初始化 在使用同一翻译单元中的任何其他内容之前, 但实际上,这将保证函数被调用 在 main 之前,或在加载 DLL 期间,如果它在 DLL 中 除了带有 main 的那个。
关于c++ - 如何在main之前预加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15013718/