Thread safe and exception safe singleton design pattern

Implement a singleton design pattern as a template such that, for any given class Foo, you can call Singleton::instance() and get a pointer to an instance of a singleton of type Foo Assume the existence of a class Lock which has acquire() and release() methods How could you make your implementation thread safe and exception safe?


using namespace std;
// Place holder for thread synchronization lock
class Lock {
	Lock() { // placeholder code to create the lock
	~Lock() { // placeholder code to deallocate the lock
	void AcquireLock() { // placeholder to acquire the lock
	void ReleaseLock() { // placeholder to release the lock

// Singleton class with a method that creates a new instance 
// of the * class of the type of the passed in template 
// if it does not already exist.
template <class T> class Singleton { 
	static Lock lock;
	static T* object; 
	Singleton() { }; 
	static T * instance(); 
Lock Singleton::lock;

T * Singleton::Instance() {
// if object is not initialized, acquire lock 
	if (object == 0) {
// If two threads simultaneously check and pass the first "if"
// condition, then only the one who acquired the lock first
// should create the instance 
		if (object == 0) {
			object = new T; 
	return object; 

int main() {
// foo is any class defined for which we want singleton access 
	Foo* singleton_foo = Singleton<Foo>::Instance();
	return 0;

The general method to make a program thread safe is to lock shared resources whenever write permission is given This way, if one thread is modifying the resource, other threads can not modify it.


1 Comment (+add yours?)

  1. Aj
    Apr 15, 2013 @ 15:47:50

    You also need to make the copy constructor private. Also, provide an empty implementation of the overloaded = operator and make it private.


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: