I have implemented a Meyer's singleton pattern. And I try to do some stuff testing it in a multithreading environment. Here is how I implemented the class in C++.
#include<thread>
#include<mutex>
class singleton {
public:
static singleton& instance() {
std::lock_guard<std::mutex> lck(mtx);
static singleton *my = new singleton;
return *my;
}
private:
static std::mutex mtx;
singleton() {}
~singleton() {}
singleton(const singleton &) {}
singleton& operator=(const singleton &) {}
};
But when I compile this with g++ -std=c++11 singleton.cpp -o singleton -lpthread
, it says
/tmp/ccfEBnmN.o: In function `singleton::instance()':
singleton.cpp(.text._ZN11singleton12instanceEv[_ZN11singelton12instanceEv]+0x10):
undefined reference to `singleton::mtx' collect2: error: ld returned 1 exit status
I understand this might be some problem in design, since without initializing the first singleton instance how could we get the mtx. If in this case, my question comes to how to implement a thread safe singleton class based on my code? How do we initialized the mtx in my singleton class?
I know there is a traditional way to create a singleton pattern by maintaining a static pointer points to the singleton class. But indeed that is not "so" thread safe. Even applying the double check mechanism in the instance() method.