欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

c++多线程单例

发布时间:2025/3/19 46 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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

转载于:https://www.cnblogs.com/xiaobaixian/p/5250438.html

总结

以上是生活随笔为你收集整理的c++多线程单例的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。