Amazon Interview Question
Software Engineer / Developersclass Singleton {
public: static Singleton *getInstance();
Singleton();
~Singleton();
Singleton(Singleton &another);
private: static Singleton *instance;
};
Singleton *Singleton::instance = 0;
Singleton *Singleton::getInstance() {
//here: obtain_lock for mutual exclusion.
if (!instance) {
instance = new Singleton();
return instance;
}
else
return instance;
}
the problem is that in multi-threaded environment, if two threads fight for a singleton object, we may have two threads with different data values. the singleton object itself exists as one, but the values within the object may be manipulated by the two threads by having its local copy and manupulation, etc...
Thus, a mutex problem. this can be solved by having lock mechnism at the location shown above.
I explained about the multithreading problem. Interviewer asked me to show the piece of the code in the singleton class that is not thread safe, then he asked how to solve the problem
- John June 23, 2007