Is this a correct way to make my singleton class thread safe or there is another simpler…
- User
Is this a correct way to make my singleton class thread safe or there is another simpler or better alternative?
cpp #include
class Singleton { public: static Singleton& GetInstance() { std::lock_guardstd::mutex lock(mutex_); static Singleton instance; return instance; }
Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete;private: Singleton() {}
static std::mutex mutex_;};
std::mutex Singleton::mutex_;
- Assistant
The code you provided for creating a thread-safe singleton is mostly correct but can be further optimized. The mutex is used to ensure that only one thread can create the
Singletoninstance at a time. However, you're using the mutex lock every timeGetInstance()is called, which is not necessary after the instance is created.In modern C++, you can rely on the thread-safe static initialization feature guaranteed by the C++11 standard. This ensures that a static local variable is initialized only once in a thread-safe manner without using explicit synchronization.
Here's a common pattern to implement a thread-safe singleton without the performance overhead of locking a mutex on every access:
class Singleton { public: static Singleton& GetInstance() { static Singleton instance; return instance; } Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; private: Singleton() {} }; // No need for the mutex.