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
- 01Naive lazy singleton
- 02Both threads see null
- 03Both create -> TWO instances
- 04Fix: Meyers' singleton
- 05C++11 guarantees one-time init
- 06Both get the SAME instance
- 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.