Bloomberg LP Interview Question
Financial Software Developersclass Singeton
{
static Singleton* instance;
Singleton();
Singleton(const Singleton& copy);
public:
static Singleton* getInstance();
}
Singleton* Singleton::instance = NULL;
Singleton* Singelton::getInstance()
{
MutexLock(mutex);
// Use RAII - Resource Acquisition is Instantiation
if(instance) {
return instance;
} else {
instance = new Singleton();
}
}
class MutexLock{ Mutex* aMutex;
public:
MutexLock(Mutex* mutex){
pthread_mutex_lock(mutex);
aMutex= mutex;
}
~MutexLock() { pthread_mutex_unlock(aMutex);
}
}
I love this question: when you think that you've nailed it, you find problems, when you solve those, you discover more and so on (I had 6 iterations and couldn't finish!), so drwolf's mouthful of vagueness is useful to distract attention of the interviewer, but provides no real answer.
Your singleton's destructor isn't thread safe. Try to make it thread safe now :)
Oh, actually, I wrote too fast -- BEFORE trying to think about thread safety of the destructor, solve your memory leak problem (the leak isn't that important, I understand that, but the fact that your destructor isn't called at all is quite bad, if you hold some system resources locked). So, first solve the bug in your code, then try to deal with the thread safety. It's fun, I promise.
Objective of singleton pattern is to have only one instance of the class being present at any time, but if such a class exists in a multi-threaded environment, 2 threads might simul try to create a obj of the class considering no instance exists so far.So each thread should check if there exists one before it creates and that block of code should be mutually exclusive
Objective of singleton pattern is to have only one instance of the class being present at any time, but if such a class exists in a multi-threaded environment, 2 threads might simul try to create a obj of the class considering no instance exists so far.So each thread should check if there exists one before it creates and that block of code should be mutually exclusive
1. singleton : a design pattern that is used to restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. (from Wikipedia) In a multithread program, we have to pay attention on the process of singleton class instantiation because multiple threads are in progress of intatiating the class.
- drwolf February 25, 20092. thread-safety: For making singleton design pattern thread-safe, we can make use of mutex. In a nutshell, thread-safety means that we can make sure the correctness of execution result even if any routine or program is executed by multiple threads at the same time. In the meantime, one can address re-entrant if the routine can be executed by multiple threads simultaneously and if the correctness of execution result can be guaranteed.