I was reading this-link that talks about making a singleton implementation thread safe.
Excerpt from the link:
Making the classic Singleton implementation thread safe is easy. Just acquire a lock before testing pInstance:
Singleton* Singleton::instance() {
Lock lock; // acquire lock (params omitted for simplicity)
if (pInstance == 0) {
pInstance = new Singleton;
}
return pInstance;
} // release lock (via Lock destructor)
As few things were omitted for simplicity in the above program, I thought I should write a sample code similar to what was suggested above.
This is what I wrote:
class Singleton {
public:
static Singleton* instance();
~Singleton();
void disp() { cout << "disp() called"<< endl; }
private:
static std::mutex mu2;
static Singleton* pInstance;
};
std::mutex Singleton::mu2;
Singleton* Singleton::pInstance = NULL;
Singleton* Singleton::instance() {
mu2.lock();
if (pInstance == 0) {
pInstance = new Singleton;
}
return pInstance;
}
Singleton::~Singleton() {
cout << "destructor called." << endl;
mu2.unlock();
}
void f1() {
Singleton *p = Singleton::instance();
p->disp();
}
int main()
{
std::thread t1(f1);
t1.join();
getchar();
return 0;
}
Output:
disp() called
f:\dd\vctools\crt\crtw32\stdcpp\thr\mutex.c(51): mutex destroyed while busy
My question is:
- What would be the implementation code of singleton class as per link's writer? without omitting anything?
- Why my sample program is getting runtime error.
- Is it possible to unlock the mutex in destructor?
I am running this code on Visual Studio.
Thank you.