Re: Thread safe Singleton class
On Jun 26, 3:50 am, Udit Sharma <sharmaa.u...@gmail.com> wrote:
Hi,
I was informed by my colleague that the following code is not thread
safe but I still don't know why because his arguments weren't very
convincing.
//Singleton.h
class Singleton
{
private:
static Singleton instance;
Singleton(){}
Singleton(const Singleton&){}
Singleton& operator=(Singleton const&){}
public:
static Singleton& getInstance();
};
//Singleton.cpp
#include "Singleton.h"
Singleton Singleton::instance;
Singleton& Singleton::getInstance()
{
return instance;
}
Since am maintaining a static instance this should be created only
once irrespective of how many threads are accessing the getInstance()
function at the same time. So is this code not thread safe?
As Bart van Ingen Schenau and James Kanze have said, it's thread-safe
as is, but there's the static initialization order problem. Generally,
you solve this problem either with library support ala pthread_once,
or you make your singleton instance be a function local static to
"initialize on demand" to solve the static initialization order
problem, and then you make a global whose sole purpose is to
initialize the singleton before main(), and thus presumably before
there are threads. (If there are nontrivial threads before main, you
cannot solve this problem with mutexes alone in C++. You would need
the power of pthread_once or equivalent.)
Ex:
//hpp
class singleton
{
public:
static singleton& getSingleton();
};
//cpp
singleton& singleton::getSingleton()
{ static singleton * x = new singleton;
return *x;
}
namespace { bool forceInit = (singleton::getSingleton(), true); }
This will generally ensure a single initialization of a singleton in a
thread safe way, and avoid the static order initialization problem.
(At least under the assumption that there are no threads before main.
If there are nontrivial threads before main, see pthread_once, and
good luck for non-posix systems like windows. I haven't looked into
it.) This will in no way guarantee thread-safe access to the
singleton; if the singleton is changeable you still need to worry
about guarding access such as with a mutex inside the singleton
instance. (Specifically do not make the mutex another static member of
the class, because then you run into how to safely initialize the
mutex and you hit the exact same issues as above: namely static
initialization order and thread safety of construction.)