码迷,mamicode.com
首页 > 编程语言 > 详细

C++ Singleton + MultiThread

时间:2014-10-18 00:45:37      阅读:226      评论:0      收藏:0      [点我收藏+]

标签: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++ Singleton + MultiThread

标签:c++   concurrency   multi-threading   singleton   

原文地址:http://blog.csdn.net/jsc0218/article/details/40194851

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!