Search⌘ K

Classical Meyers Singleton

Explore the Meyers Singleton implementation to understand how it achieves thread-safe initialization of a singleton in C++. Learn about the challenges of non-thread-safe methods in C++03 and how using a static local variable and the volatile keyword prevents unwanted compiler optimizations. This lesson sets the foundation for the improvements introduced in C++11 concerning thread safety in singleton patterns.

We'll cover the following...

Here is the sequential program. The getInstance method is not thread-safe with the C++03 standard.

C++
// singletonSingleThreaded.cpp
#include <chrono>
#include <iostream>
constexpr auto tenMill = 10000000;
class MySingleton{
public:
static MySingleton& getInstance(){
static MySingleton instance;
volatile int dummy{};
return instance;
}
private:
MySingleton() = default;
~MySingleton() = default;
MySingleton(const MySingleton&) = delete;
MySingleton& operator=(const MySingleton&) = delete;
};
int main(){
constexpr auto fourtyMill = 4 * tenMill;
const auto begin= std::chrono::system_clock::now();
for ( size_t i = 0; i <= fourtyMill; ++i){
MySingleton::getInstance();
}
const auto end = std::chrono::system_clock::now() - begin;
std::cout << std::chrono::duration<double>(end).count() << std::endl;
}

As the reference implementation, I use the so-called Meyers Singleton, named after ...