Thread-Safe Singleton in C++

Difficulty: MEDIUMCategory: LLDFrequency: 1Asked On 2025-05-07

Problem Statement

Design a Singleton class in C++ that ensures only one instance exists throughout the program. The implementation must be thread-safe, meaning multiple threads can safely access the singleton instance without creating multiple instances or causing race conditions.


✅ Functional Requirements


1.Singleton Properties
•Only one instance of the class should exist.
•Provide a global access point to the instance.
•Ensure lazy initialization (instance is created only when first accessed).
2.Thread-Safety
•Multiple threads accessing the singleton simultaneously should never create multiple instances.
•Minimize locking overhead for performance.
3.Accessibility
•Provide a method:
1 2static Singleton& getInstance();
•Prevent copying or assignment: delete copy constructor and assignment operator.
1.Optional Features
•Support destruction of singleton (optional, for memory cleanup).
•Support static initialization alternative for simplicity.


🔐 Constraints & Assumptions


•Language: C++
•Focus on in-memory instance; no persistence or external storage required.
•Target environment: multi-threaded (use of mutexes or C++11 thread-safe static initialization).
•Must handle potential race conditions.


🧱 Key Components


•Singleton Class
1 2class Singleton { 3private: 4 Singleton(); // Private constructor 5 ~Singleton(); 6 Singleton(const Singleton&) = delete; // Delete copy constructor 7 Singleton& operator=(const Singleton&) = delete; // Delete assignment operator 8 static Singleton* instance; 9 static std::mutex mtx; // For thread-safe creation 10public: 11 static Singleton& getInstance(); // Accessor 12};
•Thread-Safe Access Mechanisms
•Mutex Locking: lock during instance creation.
•Double-Checked Locking: reduce lock overhead.
•C++11 Static Local Variable: leverage thread-safe static initialization.


🔄 Example Workflow


1.First Call:
•Thread A calls getInstance() → instance is null → create instance → return reference.
2.Subsequent Calls:
•Thread B calls getInstance() → instance exists → immediately return reference.
3.Thread Safety Check:
•Multiple threads call getInstance() simultaneously → ensure only one instance is created.


🧪 Expected Deliverables


•C++ class implementation of thread-safe singleton.
•Test cases demonstrating:
•Only one instance is ever created.
•Multiple threads calling getInstance() concurrently get the same instance.
•Discussion of trade-offs: mutex overhead vs static initialization.


💡 Discussion Points in LLD


•Different approaches: Mutex, Double-Checked Locking, Static Local Variable.
•Lazy initialization vs eager initialization.
•Handling destruction safely in multi-threaded programs.
•Use-cases of singleton in real systems (e.g., configuration manager, logging).


Solution

Comments