#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++ Singleton + MultiThread
最新推荐文章于 2019-10-29 10:58:59 发布