#include <iostream>
#include <thread>
#include <mutex>
class Singleton {
public:
# if 0
static Singleton& getInstance() {
static Singleton instance;
return instance;
}
#endif
static Singleton* getInstance() {
std::lock_guard<std::mutex> lck(mtx);
if (nullptr == instance) {
instance = new Singleton();
}
return instance;
}
void printTest() {
std::cout << "Singleton..." << std::endl;
}
private:
Singleton() {}
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
static std::mutex mtx;
static Singleton* instance;
};
Singleton* Singleton::instance = nullptr;
std::mutex Singleton::mtx;
int main() {
Singleton::getInstance()->printTest();
return 0;
}