How to Create a Thread-Safe Singleton Pattern in Windows

How can I create a thread-safe singleton pattern in Windows?

If you are are using Visual C++ 2005/2008 you can use the double checked locking pattern, since "volatile variables behave as fences". This is the most efficient way to implement a lazy-initialized singleton.

From MSDN Magazine:

Singleton* GetSingleton()
{
volatile static Singleton* pSingleton = 0;

if (pSingleton == NULL)
{
EnterCriticalSection(&cs);

if (pSingleton == NULL)
{
try
{
pSingleton = new Singleton();
}
catch (...)
{
// Something went wrong.
}
}

LeaveCriticalSection(&cs);
}

return const_cast<Singleton*>(pSingleton);
}

Whenever you need access to the singleton, just call GetSingleton(). The first time it is called, the static pointer will be initialized. After it's initialized, the NULL check will prevent locking for just reading the pointer.

DO NOT use this on just any compiler, as it's not portable. The standard makes no guarantees on how this will work. Visual C++ 2005 explicitly adds to the semantics of volatile to make this possible.

You'll have to declare and initialize the CRITICAL SECTION elsewhere in code. But that initialization is cheap, so lazy initialization is usually not important.

Thread Safe C# Singleton Pattern

Performing the lock is terribly expensive when compared to the simple pointer check instance != null.

The pattern you see here is called double-checked locking. Its purpose is to avoid the expensive lock operation which is only going to be needed once (when the singleton is first accessed). The implementation is such because it also has to ensure that when the singleton is initialized there will be no bugs resulting from thread race conditions.

Think of it this way: a bare null check (without a lock) is guaranteed to give you a correct usable answer only when that answer is "yes, the object is already constructed". But if the answer is "not constructed yet" then you don't have enough information because what you really wanted to know is that it's "not constructed yet and no other thread is intending to construct it shortly". So you use the outer check as a very quick initial test and you initiate the proper, bug-free but "expensive" procedure (lock then check) only if the answer is "no".

The above implementation is good enough for most cases, but at this point it's a good idea to go and read Jon Skeet's article on singletons in C# which also evaluates other alternatives.

Thread Safe Singleton Class - Am I doing this Right?

Yours is not idiomatic singleton, because it is still prone to so-called "static initialization order fiasco".

An idiomatic singleton doesn't have a static class member, instead it's instance function looks like

static MySingleton& instance() {
static MySingleton the_ton;
return the_ton;
}

More on the fiasco: static initialization order fiasco

Is Meyers' implementation of the Singleton pattern thread safe?

In C++11, it is thread safe. According to the standard, §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.

GCC and VS support for the feature (Dynamic Initialization and Destruction with Concurrency, also known as Magic Statics on MSDN) is as follows:

  • Visual Studio: supported since Visual Studio 2015
  • GCC: supported since GCC 4.3

Thanks to @Mankarse and @olen_gam for their comments.


In C++03, this code wasn't thread safe. There is an article by Meyers called "C++ and the Perils of Double-Checked Locking" which discusses thread safe implementations of the pattern, and the conclusion is, more or less, that (in C++03) full locking around the instantiating method is basically the simplest way to ensure proper concurrency on all platforms, while most forms of double-checked locking pattern variants may suffer from race conditions on certain architectures, unless instructions are interleaved with strategically places memory barriers.

How to implement multithread safe singleton in C++11 without using <mutex>

C++11 removes the need for manual locking. Concurrent execution shall wait if a static local variable is already being initialized.

§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.

As such, simple have a static function like this:

static Singleton& get() {
static Singleton instance;
return instance;
}

This will work all-right in C++11 (as long as the compiler properly implements that part of the standard, of course).


Of course, the real correct answer is to not use a singleton, period.

Thread Safe Singletons in Java

Answer 1: static synchronized methods use the class object as the lock - ie in this case Singleton.class.

Answer 2: The java language, among other things:

  • loads classes when they are first accessed/used
  • guarantees that before access to a class is allowed, all static initializers have completed

These two facts mean that the inner static class SingletonHolder is not loaded until the getInstance() method is called. At that moment, and before the thread making the call is given access to it, the static instance of that class is instantiated as part of class loading.

This all means we have safe lazy loading, and without any need for synchronization/locks!

This pattern is the pattern to use for singletons. It beats other patterns because MyClass.getInstance() is the defacto industry standard for singletons - everyone who uses it automatically knows that they are dealing with a singleton (with code, it's always good to be obvious), so this pattern has the right API and the right implementation under the hood.

btw Bill Pugh's article is worth reading for completeness when understanding singleton patterns.

Making a program with singletons multithreaded C#

The easiest way is to move all calculations to one separate thread and update the GUI using Invoke/InvokeRequired.

public partial class MyForm : Form
{
Thread _workerThread;

public MyForm()
{
_workerThread = new Thread(Calculate);
}

public void StartCalc()
{
_workerThread.Start();
}

public void Calculate()
{
//call singleton here

}

// true if user are allowed to change calc settings
public bool CanUpdateSettings
{
get { return !_workerThread.IsAlive; } }
}
}

In this way you have get a response GUI while the calculations are running.

The application will be thread safe as long as you don't allow the user to make changes during a running calculation.

Using several threads for doing the calculations is a much more complex story which we need more information for to give you a proper answer.

Creating thread-safe singleton wrapper for DI container

To implement a thread-safe singleton pattern you have two options basically:

1.Double-checked locking

public static NinjectResolver GetInstance()
{
if(instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new NinjectResolver();
}
}
return instance;
}

2.Initialize the instance upon declaration

private static volatile NinjectResolver instance = new NinjectResolver();

public static NinjectResolver GetInstance()
{
return instance;
}

Also you can drop the code inside the static block and just use:

private static volatile IKernel kernel = new StandardKernel();

C++ Singleton design pattern

In 2008 I provided a C++98 implementation of the Singleton design pattern that is lazy-evaluated, guaranteed-destruction, not-technically-thread-safe:

Can any one provide me a sample of Singleton in c++?

Here is an updated C++11 implementation of the Singleton design pattern that is lazy-evaluated, correctly-destroyed, and thread-safe.

class S
{
public:
static S& getInstance()
{
static S instance; // Guaranteed to be destroyed.
// Instantiated on first use.
return instance;
}
private:
S() {} // Constructor? (the {} brackets) are needed here.

// C++ 03
// ========
// Don't forget to declare these two. You want to make sure they
// are inaccessible(especially from outside), otherwise, you may accidentally get copies of
// your singleton appearing.
S(S const&); // Don't Implement
void operator=(S const&); // Don't implement

// C++ 11
// =======
// We can use the better technique of deleting the methods
// we don't want.
public:
S(S const&) = delete;
void operator=(S const&) = delete;

// Note: Scott Meyers mentions in his Effective Modern
// C++ book, that deleted functions should generally
// be public as it results in better error messages
// due to the compilers behavior to check accessibility
// before deleted status
};

See this article about when to use a singleton: (not often)

Singleton: How should it be used

See this two article about initialization order and how to cope:

Static variables initialisation order

Finding C++ static initialization order problems

See this article describing lifetimes:

What is the lifetime of a static variable in a C++ function?

See this article that discusses some threading implications to singletons:

Singleton instance declared as static variable of GetInstance method, is it thread-safe?

See this article that explains why double checked locking will not work on C++:

What are all the common undefined behaviours that a C++ programmer should know about?

Dr Dobbs: C++ and The Perils of Double-Checked Locking: Part I



Related Topics



Leave a reply



Submit