
Hello Moshe, Thursday, February 8, 2007, 12:42:26 PM, you wrote:
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.:
[snip] Yes, theoretically it is possible. I guess, I've never met the code that spawns a thread during module loading process. I have to admit though that such code is not safe itself (with no regard to the singleton issue). The thread spawns at the moment when global initialization is not finished and it cannot catch the moment when it is. This means that it may not safely access any global data in the first place, including the singleton. So if such code is written, the developer should have beared in mind that the thread should be isolated at least until the initialization is completed. And the main thread can tell the spawned thread when it is completed, which may be done after the singleton construction, of course. So, I agree that it is possible. But if the developer is not foe to himself, he should have taken necessary precautions.
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.
The library loading process is usually made though OS API which synchronizes internally. That makes library initialization thread-safe, unless it spawns a thread as you noted above. -- Best regards, Andrey mailto:andysem@mail.ru