C++ Static Initializer - Is it thread safe -
usually, when try initialize 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 following code thread safe, during static variable initialization?
- is there better way static initialize stringlist, instead of using seperate static function (init)?
although initialization shall happen before main function (hence, there can no threads simultaneous access init), concern :
- i have exe application.
- my exe application load a.dll, b.dll , c.dll
- a/b/c.dll, in turn load common.dll. above code inside common.dll
- i had verify. since 3 dll within single process, referring same static variable (vector).
- in case, prevent 3 dlls simultaneous access init (can view them 3 threads? although doesn't make sense @ first thought), init function, shall use critical section protect it?
i using windows xp, vc6 , vc2008 compiler.
i asked similar question while back:
when comes dlls, static initialization , call dllmain bracketed internal critical section, thread-safe. second thread wait until first done before loads dll.
so in short, static init safe.
Comments
Post a Comment