design patterns · high

Thread-Safe Singleton

Why the naive lazy singleton is a data race, and how a function-local static (Meyers' singleton) gives thread-safe, lazy, single init.

🔑 Key line

Naive lazy singleton races (two threads create two instances); a function-local static (Meyers') initializes once, thread-safely since C++11.

The code

// Naive (BROKEN under threads)
Singleton* getInstance() {
if (!instance) // race: two threads see null
instance = new Singleton();
return instance;
}
// Meyers' singleton (thread-safe since C++11)
Singleton& getInstance() {
static Singleton inst; // initialized once, thread-safely
return inst;
}

What this lesson walks through

  1. 01Naive lazy singleton
  2. 02Both threads see null
  3. 03Both create -> TWO instances
  4. 04Fix: Meyers' singleton
  5. 05C++11 guarantees one-time init
  6. 06Both get the SAME instance
  7. 07When you can't use a static local

The classic lazy singleton: if the instance pointer is null, create it. This looks fine single-threaded.

See it animated — step by step, at your own pace

Unlock the full interactive walkthrough of Thread-Safe Singleton and 100+ animated C++ interview lessons.

← Previous
SOLID Principles — C++ Examples, Violations, and Interview Self-Check
Next →
GoF Factory Method — Deferred Object Creation via Subclasses