Problem
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?
Solution
Here is the code in cpp:
using namespace std;
// Place holder for thread synchronization lock
class Lock {
public:
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 {
private:
static Lock lock;
static T* object;
protected:
Singleton() { };
public:
static T * instance();
};
Lock Singleton::lock;
T * Singleton::Instance() {
// if object is not initialized, acquire lock
if (object == 0) {
lock.AcquireLock();
// 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;
}
lock.ReleaseLock();
}
return object;
}
int main() {
// foo is any class defined for which we want singleton access
Foo* singleton_foo = Singleton<Foo>::Instance();
return 0;
}
Thanks
References







0 comments:
Post a Comment