讲解来自:http://blog.chinaunix.net/xmlrpc.php?r=blog/article&id=4281275&uid=26611383

由于使用了POSIX函数,所以下面的代码只能运行在*NIX系统中。

#include<pthread.h>
#include<stdio.h> template <typename T>
class Singleton {
public:
static T& GetInstance() {
if (value_ == NULL) {
pthread_mutex_lock(&thread_lock_);
if (value_ == NULL) {
T* temp = new T();
value_ = temp;  
          atexit(Destroy);
}
pthread_mutex_unlock(&thread_lock_); }
return *value_;
} private:
Singleton();
~Singleton();
Singleton(const Singleton& rhs);
Singleton& operator=(const Singleton& rhs); void Destroy() {
if (value_ == NULL) {
delete value_;
value_ = NULL;
}
} private:
static pthread_mutex_t thread_lock_;
static T* value_;
}; template<typename T>
pthread_mutex_t Singleton<T>::thread_lock_ = PTHREAD_MUTEX_INITIALIZER; template<typename T>
T* Singleton<T>::value_ = NULL;

刚发现C++11提供了mutex关键字,所以我们有了可移植版本:

template <typename T>
class Singleton {
public:
static T& GetInstance() {
if (value_ == NULL) {
std::lock_guard<std::mutex> lck(mt);
if (value_ == NULL) {
T* temp = new T();
value_ = temp;            
atexit(Destroy);
} }
return *value_;
} private:
Singleton();
~Singleton();
Singleton(const Singleton& rhs);
Singleton& operator=(const Singleton& rhs); void Destroy() {
if (value_ == NULL) {
delete value_;
value_ = NULL;
}
} private:
static std::<mutex> mt;
static T* value_;
}; template<typename T>
T* Singleton<T>::value_ = NULL;

参考资料:

  http://blog.poxiao.me/p/multi-threading-in-cpp11-part-2-mutex-and-lock/#C++11%E4%B9%8B%E5%A4%9A%E7%BA%BF%E7%A8%8B%E7%B3%BB%E5%88%97%E6%96%87%E7%AB%A0%E7%9B%AE%E5%BD%95

其他非常有价值的资料:

  1. http://liyuanlife.com/blog/2015/01/31/thread-safe-singleton-in-cxx/

  2. https://github.com/chenshuo/muduo/blob/master/muduo/base/Singleton.h

  3. http://www.cnblogs.com/loveis715/archive/2012/07/18/2598409.html

05-23 06:40