Avoid locking in Singleton

The Singleton is a useful Design Pattern which allows only one instance of your class. Singleton is implemented by declaring static instance of the object reference within the class

class MySingleton {
static MySingleton *instance;
MySingleton() {
//...
}

public:
MySingleton* getInstance() {
return instance;
}

}

static MySingleton::instance= new MySingleton();

If singleton object is created during loading time itself, no locking is required. But in case of lazy loading, it needs to be guarded with a mutex to avoid multiple object instantiation.

MySingleton* getInstance() {

 //acquire mutex
if (NULL == instance) {
instance = new MySingleton();

 }

  //release mutex
return instance;
}

Every request to getInstance() includes mutex overhead.In order to avoid mutex overhead, double checked locking pattern can be used.

// Double-checked locking -- don't use
MySingleton* getInstance() {
if (NULL == instance) {
//acquire mutex
if (NULL==instance) {
instance = new MySingleton();
}
//release mutex
}
}

This method is not 100% safe because of compiler optimizations and may lead to undefined behavior which is hard to debug. Another technique(safe to use) is to use atomic operations and local variable as specified below.


MySingleton* getInstance() {
MySingleton *localRef = new MySingleton();

  int ret = testandset(&instance, 0, localRef);

  //note testandset function returns old value stored in the variable.
if (0==ret) {
return instance;
}
//some other thread had initialized this.

  delete localRef;

  return instance;
}

Advertisements

One thought on “Avoid locking in Singleton

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s