Singleton is not thread-safe in C++.
Query : How does multiple threads affects Singleton?
Response : Lets assume that no instance of Singleton class is created yet. Two threads try to access the getInstance() function at the same time. The 1st thread checks if instance is NULL or not. Meanwhile the thread switching happens and the second thread checks if the instance is NULL or not. This will lead to both the thread trying to allocate memory to instance. On subsequent calls of getInstance() the issue won't be there but may lead to issue on that particular occasion.
Query : How to make Singleton thread safe?
Response : Put a mutex-lock in the getInstance() function. It is recommended to put the lock after the check for instance being NULL as lock is a costly operation and only required during initialization. Also, add another check for instance being NULL so the second thread can fail on this check.
std::mutex m;
Single* Single::getInstance()
{
if(!instance)
{
m.lock();
if(!instance)
{
instance = new Single();
}
m.unlock();
}
return instance;
}
No comments:
Post a Comment