c++多线程单例
单例写在一个头文件中就行,所有函数都是一句类似内敛函数实现
需要注意的是一下几点:
1 在一个大的工程中,单例模式往往不只是针对一种类型,所有使用模板。
2 如果是多线程,要考虑所有线程只初始化一次
3 程序退出的时候,释放内存,因为是用静态方式,所以,注册atexit退出函数,另外一个是使用只能指针。
#ifndef SINGLETON_H
#define SINGLETON_H
#include <string>
#include <stdio.h>
#include <boost/noncopyable.hpp>
#include <pthread.h>
#include <stdlib.h>
namespace common
{
template<typename T>
class Singleton : boost::noncopyable
{
public:
static T& instance()
{
pthread_once(&once_, &Singleton::init);
return *instance_;
}
private:
Singleton();
~Singleton();
static void init()
{
instance_ = new T();
::atexit(destroy);
}
static void destroy()
{
typedef char has_define[(sizeof(T) == 0 ? -1:1)];
has_define dummy;
(void) dummy;
delete instance_;
}
private:
static T* instance_;
static pthread_once_t once_;
};
template<typename T>
T* Singleton<T>::instance_ = NULL;
template<typename T>
pthread_once_t Singleton<T>::once_ = PTHREAD_ONCE_INIT;
}
#endif