I was reading about the Singleton design pattern and how to implement it thread-safe.
All went well until the authors said: “In reality, we need a lock only when initializing instance. That should occur only the first time instance is called”
and this is the implementation:
Singleton* Singleton::instance()
{
if (instance == nullptr) {
std::lock_guard<std::mutex> lock(mutex_);
if (instance == nullptr) {
Singleton* temp = new Singleton;
instance = temp;
}
}
return instance;
}
But I am concerned about saying that we only need a mutex while creating the instance. WHY?
Consider a case when you have a method inside the singleton class that modifies a common value based on a previous one. Am I right?