Usually, when I try to initialize a static variable
class Test2 {
public:
static vector<string> stringList;
private:
static bool __init;
static bool init() {
stringList.push_back("string1");
stringList.push_back("string2");
stringList.push_back("string3");
return true;
}
};
// Implement
vector<string> Test2::stringList;
bool Test2::__init = Test2::init();
- Is the following code thread safe, during static variable initialization?
- Is there any better way to static initialize stringlist, instead of using a seperate static function (init)?
Although the initialization shall happen before main function (Hence, there can be no threads to simultaneous access the init), my concern is that :
- I have an exe application.
- My exe application will load a.dll, b.dll and c.dll
- a/b/c.dll, in turn will load common.dll. The above code are inside common.dll
- I had already verify. Since 3 dll are within single process, they will be referring to the same static variable (vector).
- In this case, to prevent 3 dlls from simultaneous access init (Can I view them as 3 threads? Although doesn’t make sense at first thought), for the init function, shall I use a critical section to protect it?
I am using Windows XP, VC6 and VC2008 compiler.
I asked a similar question a while back:
LoadLibrary and Static Globals
When it comes to DLLs, static initialization and the call to DllMain is bracketed by an internal critical section, so they are thread-safe. A second thread will wait until the first is done before it loads the DLL.
So in short, your static init is safe.