
On Tuesday, February 06, 2007 8:09 PM, Andrey Semashev wrote:
Tuesday, February 6, 2007, 1:34:50 AM, you wrote:
...
What kind of solutions have you come up with for lazily initializing singletons in a thread-safe manner?
In most cases I tried not to create the singleton lazily but initialize it as soon as possible. The perfect time is on executable module load which, AFAIK, is always done in single thread on platforms I have faced yet. Such approach was quite sufficient for me since it solves the key problem of the singleton creation.
I don't see how such an assumption can be made. What if a thread is started in the constructor or initializer of a global object? I.e.: void thread_func() { // This may be called before, or concurrently with, // your singleton early-initialization function singleton::instance()->do_something(); } class foo { foo() { boost::thread my_thread (&thread_func); } }; // Constructed on module load foo global_foo; Then there's the issue of singletons located in shared libraries (on *nix platforms) or DLL's (on Windows). If these modules are loaded dynamically, there may already be multiple threads running. Moshe