标签:c++ concurrency multi-threading singleton
#include <iostream> #include <mutex> using namespace std; template <class T> class Singleton { public: static T *instance() { if (object == NULL) { mtx.lock(); if (object == NULL) object = new T; mtx.unlock(); } return object; } private: Singleton() {} // be here? necessary? static T *object; static mutex mtx; }; template <class T> T* Singleton<T>::object = NULL; template <class T> mutex Singleton<T>::mtx; class Foo { }; int main() { Foo *singletonFoo = Singleton<Foo>::instance(); return 0; }
标签:c++ concurrency multi-threading singleton
原文地址:http://blog.csdn.net/jsc0218/article/details/40194851