Singleton instance declared as static variable of GetInstance method, is it thread-safe? [duplicate]
Asked Answered
G

4

33

I've seen implementations of Singleton patterns where instance variable was declared as static variable in GetInstance method. Like this:

SomeBaseClass &SomeClass::GetInstance()
{
   static SomeClass instance;
   return instance;
}

I see following positive sides of this approach:

  • The code is simpler, because it's compiler who responsible for creating this object only when GetInstance called for the first time.
  • The code is safer, because there is no other way to get reference to instance, but with GetInstance method and there is no other way to change instance, but inside GetInstance method.

What are the negative sides of this approach (except that this is not very OOP-ish) ? Is this thread-safe?

Gauss answered 16/1, 2009 at 3:44 Comment(0)
K
49

In C++11 it is thread safe:

§6.7 [stmt.dcl] p4 If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.

In C++03:

  • Under g++ it is thread safe.
    But this is because g++ explicitly adds code to guarantee it.

One problem is that if you have two singletons and they try and use each other during construction and destruction.

Read this: Finding C++ static initialization order problems

A variation on this problem is if the singleton is accessed from the destructor of a global variable. In this situation the singleton has definitely been destroyed, but the get method will still return a reference to the destroyed object.

There are ways around this but they are messy and not worth doing. Just don't access a singleton from the destructor of a global variable.

A Safer definition but ugly:
I am sure you can add some appropriate macros to tidy this up

SomeBaseClass &SomeClass::GetInstance()
{
#ifdef _WIN32 
Start Critical Section Here
#elif  defined(__GNUC__) && (__GNUC__ > 3)
// You are OK
#else
#error Add Critical Section for your platform
#endif

    static SomeClass instance;

#ifdef _WIN32
END Critical Section Here
#endif 

    return instance;
}
Krute answered 16/1, 2009 at 8:20 Comment(2)
Does "§6.7 [stmt.dcl] p4 If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization.", this also apply to global static variables? ThanksBurt
@Burt static on a global variable means something different: the variable has internal linkage. Only the translation unit containing the variable can see and directly interact with it. Note that if you have the same identifier in multiple translation units they are all different instances with the same name and static prevents them from colliding when the linker assembles the program. It can only be initialized once at program start-up so threading is not an issue.Rowen
S
5

It is not thread safe as shown. The C++ language is silent on threads so you have no inherent guarantees from the language. You will have to use platform synchronization primitives, e.g. Win32 ::EnterCriticalSection(), to protect access.

Your particular approach would be problematic b/c the compiler will insert some (non-thread safe) code to initialize the static instance on first invocation, most likely it will be before the function body begins execution (and hence before any synchronization can be invoked.)

Using a global/static member pointer to SomeClass and then initializing within a synchronized block would prove less problematic to implement.

#include <boost/shared_ptr.hpp>

namespace
{
  //Could be implemented as private member of SomeClass instead..
  boost::shared_ptr<SomeClass> g_instance;
}

SomeBaseClass &SomeClass::GetInstance()
{
   //Synchronize me e.g. ::EnterCriticalSection()
   if(g_instance == NULL)
     g_instance = boost::shared_ptr<SomeClass>(new SomeClass());
   //Unsynchronize me e.g. :::LeaveCriticalSection();
   return *g_instance;
}

I haven't compiled this so it's for illustrative purposes only. It also relies on the boost library to obtain the same lifetime (or there about) as your original example. You can also use std::tr1 (C++0x).

Scheer answered 16/1, 2009 at 6:32 Comment(3)
Yes use critical section on windows. G++ guarantees that only one thread will initialize it.Krute
Create a second, private method _getInstance() that actually contains the definition of the static instance, then have the (public) GetInstance() method calls that method in between OS-specific synch primitives. C++ cannot reorder in this case, and you avoid a heap allocation.Floatplane
@j_random_hacker: Yeah that's a neat idea. @Martin York: Thanks for the tip about g++ I did not know that.Scheer
D
1

According to specs this should also work in VC++. Anyone know if it does?

Just add keyword volatile. The visual c++ compiler should then generate mutexes if the doc on msdn is correct.

SomeBaseClass &SomeClass::GetInstance()
{
   static volatile SomeClass instance;
   return instance;
}
Durable answered 18/8, 2010 at 15:25 Comment(2)
Which doc is that? For instance msdn.microsoft.com/en-us/library/12a04hfd.aspx does not mention mutex.Woodyard
volatile has nothing to do with thread safetyChummy
H
-12

It shares all of the common failings of Singleton implementations, namely:

  • It is untestable
  • It is not thread safe (this is trivial enough to see if you imagine two threads entering the function at the same time)
  • It is a memory leak

I recommend never using Singleton in any production code.

Hansel answered 16/1, 2009 at 4:7 Comment(13)
The question isn't related to singleton pattern usage, but to it's particular implementation.Gauss
This particular implementation has all of those failings. Please feel free to argue the point any time you likeHansel
Or you know, just vote down silently. It's all the same to meHansel
Actually this IS thread safe under G++. The compiler has logic that guarantees that only one thread will initialise static function members.Krute
Can't argue with the general recommendation as Singeltons are extremly hard to use correctly. But everything has a use. I just can't think of one.Krute
It is not thread safe in C++, just because it happens to be thread safe in some non-standard implementation doesn't change that factHansel
I am sure MS will not be long before they add it and with the new C++ standard coming soon and being thread aware it will (hopefully) be fixed here. But technically you are correct.Krute
It is testable. But what I think you mean is that it makes testing other things that use a singleton harder, but this is still not imposable.Krute
I think you'll find that mine and your definition of "testable" are different. You should have a good read of the google testing blog (link given above). Testability depends on being able to replace external components (such as your singleton) with a mock - the Singleton implementation prevents thatHansel
In this specific design yes it is not possible to replace with a mock object. But this pattern is relatively easy to extend with a factory. The signgelton should not create itself it delegates this work to a factory. Different factory can be used for test and production. The test version of the factory just instantiates a mock version of the singelton.Krute
@Martin: About the leak - I guess he meant that the static instance might stick around until doom's day without ever getting used after the first use and instantiation, making it leak-ish as the memory cannot be reclaimed.Melvamelvena
@Johann Gerell: I suppose yes just like all objects with a static storage duration its space will not be reclaimed until program termination. But that's not a leak (just like a global is not a leak) as a reference to the object can be obtained. And the destructor will be called correctly. Remember this is a pattern not a design it is meant to be adaptable to the situation and it is relatively easy to adapt the pattern to release the object when no longer in use. But that is another question (maybe you should ask (It is also a common interview question))Krute
@Johann Gerell: But as emphasized above the worst thing about singeltons is they make the code exceedingly hard to test (as they are basically global state mascaraing as a pattern). This is why singeltons can not be used carelessly (to make the code testable you must be able to switch them out appropriately which requires the use of other patterns (see above where I suggest the use of a factory)).Krute

© 2022 - 2024 — McMap. All rights reserved.