c++多线程单例
單例寫在一個頭文件中就行,所有函數(shù)都是一句類似內(nèi)斂函數(shù)實現(xiàn)
需要注意的是一下幾點:
1 ? ?在一個大的工程中,單例模式往往不只是針對一種類型,所有使用模板。
?
2 ? 如果是多線程,要考慮所有線程只初始化一次
?
3 ? 程序退出的時候,釋放內(nèi)存,因為是用靜態(tài)方式,所以,注冊atexit退出函數(shù),另外一個是使用只能指針。
?
#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
轉(zhuǎn)載于:https://www.cnblogs.com/xiaobaixian/p/5250438.html
總結(jié)
- 上一篇: MAVEN POM dependenci
- 下一篇: Office 365 Exchange