I have done little work in multi-threaded environments. So, I need to know whether below class’s getInstance function is thread-safe or not. Here is singleton class :
//Singleton class
class S {
// intentionally avoided pointer
static S singleObject;
// Private constructor
s ();
s (S &);
s& operator= (const s&);
public:
// return reference of static object
s& getInstance ()
{
return singleObject;
}
/* Normally with static pointer instance, getInstnace look like as
s& getInstace ()
{
// trying to avoid multiple copies of singleObject
lock_mutex ()
if (singleObject == null)
singleObjecct = new S();
unlock_mutex ();
return *singleObject;
}
*/
};
S S::singleObject;
In getInstance function (un-commented), static object’s reference is returned. Does it requires thread-safe mechanism?
In second getInstance (commented), we create the object if singleObject is null. So, it requires a locking mechanism and needs to be synchronized, right?
As long as you don’t access it outside the lifetime of the
mainfunction, or modify it when other threads might have unsynchronised access, then it’s safe to access from any thread.If you do access before
mainstarts or after it ends (e.g. from the constructor or destructor of another static object), then there is a danger that it won’t have been initialised, or will already have been destroyed, at that point. That is the motivation for “lazy initialisation” such as your second version.Yes, that requires a locking mechanism. For compilers that support the C++11 (or similar) threading model, a simpler way to get lazy initialisation like this is to use a function-static variable, which will be initialised in a thread-safe way the first time it comes into scope:
This will also avoid the memory leak of your version, but introduces a danger that it might be destroyed before other static objects; therefore, it’s not safe to access from a static object’s destructor.
In general, static objects in C++ are a minefield of such deathtraps (whether or not you try to wrap them up in some kind of singleton anti-pattern) and are best avoided.