Wednesday, 5 September 2018

Singleton : Is it Thread Safe?


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;
}

Singleton: Destructor should be private or public?


We make sure that one instance of class is created by making constructor private. How do we release/destroy the instance?

Query : Should we delete the instance in destructor?

Response : Not in the traditional way.

The destructor will look like this

Single :: ~Single()
{
    delete instance;
}

When the 'delete instance' is called it will invoke the destructor for the instance and it will keep running in an infinite loop.

Query : When to release the Singleton Class Instance?

Response : Singleton instance is supposed to be there for the complete lifetime of the program. Once the program finishes, C++ automatically deletes static objects. However, it is recommended to write a release function to make sure to release the memory when program ends. The problem is with multiple user/thread accessing the Singleton. To make sure it ends properly have a private variable "count" of number of users having access to the class.

Single* Single::getInstance()
{
 if(!instance)
 {
  instance = new Single();
 }
    ++count;
 return instance;
}

void Single::releaseInstace()
{
    --count;
    if((count==0) && (instance!=NULL))
    {
        delete instance;
        instance=NULL;
    }
}

Note: This doesn't work if a particular user calls multiple get instance of the class but deletes only once. Also, calling releaseInstance() multiple times by same user will also lead to situation where instance is deleted while it is used by another user.

Query : Should Destructor be private or public?

Response : It is recommended to keep private destructor and a public static function to release instance as mentioned above.




Back to Singleton

Tuesday, 28 August 2018

Singleton : Introduction

The Singleton Design Pattern restricts you to have a single object of the class. It also provides options to call methods of the class without actually having the object of the class.

Query : How to not let other's create an object of the class ?

Response : Constructor is called whenever an object of the class is created. Make all the constructors as private. No one can create an object, not even by inheritance.

Query : How do we create single instance of the class?

Response : A static data member exists as member of class than instance based. There is a single instance of the static variable for all objects of the class. Similar is the case with static methods/functions. A static method can be called even if no object of class is present. Static method can be accessed using class name and scope resolution operator (::). To achieve single instance of the class, we create a class variable which is static and private. We return this variable with help of a public static function. A public static function can be called without class object. It can call the private constructor of the class also.


Simple example Of Singleton in C++

Single.h

#include<iostream>

using namespace std;

Class Single
{
private:
 Single() {};
    Single(const Single &){};
 static Single *instance;
public:
 static Single *getInstance();
};

Single.cpp

#include<single.h>

Single* Single::instance=NULL;

Single* Single::getInstance()
{
 if(!instance)
 {
  instance = new Single();
 }
 return instance;
}



Should Destructor be private or public?

Is it Thread Safe?





Singleton : Is it Thread Safe?

Singleton is not thread-safe in C++. Query : How does multiple threads affects Singleton? Response : Lets assume that no instance of...