Reputation: 4459
To my understanding, if the Singleton::instance() is called in different thread, there might be some problem if both call refer to the first construction of the actual instance.
So if I move the first Singleton::instance() call to the very beginning of the program where no other threads are even created, will this be thread safe now?
Of course, all its member variable are protected by mutex guard when used.
Upvotes: 0
Views: 127
Reputation: 123
If there is no additional thread created yet and you make that move before those threads creation, I don't see a real scenario where you might have problems by using the singleton you already created in any new created multi-threaded environment.
The main thread-safe problem of singleton pattern into a multi-threaded environment is about how to prevent two or more "singleton" instances creation by different threads. I have described this scenario into "Multi-threaded environment" section here.
Upvotes: 0
Reputation: 49221
Just remember not to put in the header.
If you put the implementation in the header, it may be generated in every compilation unit that uses it. Which means it won't be single.
Also don't compile it in static libraries. This can also lead to multiple instances if the code is linked and merges into several non-static libraries.
Upvotes: 0
Reputation: 1181
This might open your eyes to a thread-safe Singleton and how easy it isn't. http://silviuardelean.ro/2012/06/05/few-singleton-approaches/
As per before, it's not very robust if you're requiring it to be created before any threads are kicked off.
Worth noting though, if you compile with C++11, then doing as Brian said (static storage + static method) guarantees thread safety. With any previous versions you will need a mutex, and will run into the caveats mentioned in the link I shared.
Upvotes: 4
Reputation: 1890
Maybe then you don't need lazy initialization of singleton instance?
If you actually want it then you can protect singleton instance with mutex when you construct it.
Upvotes: 0
Reputation: 14619
So if I move the first Singleton::instance() call to the very beginning of the program where no other threads are even created, will this be thread safe now?
Yes, but this element is not within the Singleton
's design and would likely be more robust if it were.
You can often allocate it at file scope or in function scope with static
storage within a static
method. Verify that your compiler generates exclusion around it or add your own mutex there.
Upvotes: 3
Reputation: 385098
Yes, performing the initial instantiation when you can guarantee there is just one thread extant clearly protects it from other threads causing race conditions.
It doesn't feel terribly robust, though. At the very least, plaster the area with warning comments.
Upvotes: 1