base::AtExitManager 和 base::Singleton 的结合使用
单例模式(Singleton)也称为单件模式,其意图是保证一个类仅有一个实例,并提供一个访问它的全局访问点,该实例被所有程序模块共享。有很多地方需要这样的功能模块,如系统的日志输出,GUI 应用必须是单鼠标,操作系统只会弹出一个任务管理器等。
在我们的项目中使用了 Chrome 提供的 base::AtExitManager 类
该类负责类的内存回收问题,AtExitManager 模仿的就是 atexit 函数的功能,使用的时候,可以在 WinMain 函数中定义一个 AtExitManager 实例:
base::AtExitManager exit_manager;
在需要创建单例的地方使用 base::Singleton,官方的 singleton.h 提供了一个例子
// Example usage:
//
// In your header:
namespace base {
template <typename T>
struct DefaultSingletonTraits;
}
class FooClass {
public:
static FooClass* GetInstance(); <-- See comment below on this.
void Bar() { ... }
private:
FooClass() { ... }
friend struct base::DefaultSingletonTraits<FooClass>; DISALLOW_COPY_AND_ASSIGN(FooClass);
}; // In your source file:
#include "base/memory/singleton.h"
FooClass* FooClass::GetInstance() {
return base::Singleton<FooClass>::get();
}
简单的说就是创建一个 GetInstance 方法,再用 base::Singleton 提供的方法创建一个指针,这个指针指向类的对象,创建对象的方法被隐藏在 base::Singleton 中,我们在调用类的方法时候,只需要
FooClass::GetInstance->bar();
好奇该类如何被创建的,可以看它的源码,大致是这样
template <typename Type,
typename Traits = DefaultSingletonTraits<Type>,
typename DifferentiatingType = Type>
class Singleton {
private:
// Classes using the Singleton<T> pattern should declare a GetInstance()
// method and call Singleton::get() from within that.
friend Type* Type::GetInstance(); // Allow TraceLog tests to test tracing after OnExit.
friend class internal::DeleteTraceLogForTesting; // This class is safe to be constructed and copy-constructed since it has no
// member. // Return a pointer to the one true instance of the class.
static Type* get() {
#if DCHECK_IS_ON()
// Avoid making TLS lookup on release builds.
/* if (!Traits::kAllowedToAccessOnNonjoinableThread)
ThreadRestrictions::AssertSingletonAllowed(); */
#endif // The load has acquire memory ordering as the thread which reads the
// instance_ pointer must acquire visibility over the singleton data.
subtle::AtomicWord value = subtle::Acquire_Load(&instance_);
if (value != 0 && value != internal::kBeingCreatedMarker) {
return reinterpret_cast<Type*>(value);
} // Object isn't created yet, maybe we will get to create it, let's try...
if (subtle::Acquire_CompareAndSwap(&instance_, 0,
internal::kBeingCreatedMarker) == 0) {
// instance_ was NULL and is now kBeingCreatedMarker. Only one thread
// will ever get here. Threads might be spinning on us, and they will
// stop right after we do this store.
Type* newval = Traits::New(); // Releases the visibility over instance_ to the readers.
subtle::Release_Store(&instance_,
reinterpret_cast<subtle::AtomicWord>(newval)); if (newval != NULL && Traits::kRegisterAtExit)
AtExitManager::RegisterCallback(OnExit, NULL); return newval;
} // We hit a race. Wait for the other thread to complete it.
value = internal::WaitForInstance(&instance_); return reinterpret_cast<Type*>(value);
} // Adapter function for use with AtExit(). This should be called single
// threaded, so don't use atomic operations.
// Calling OnExit while singleton is in use by other threads is a mistake.
static void OnExit(void* /*unused*/) {
// AtExit should only ever be register after the singleton instance was
// created. We should only ever get here with a valid instance_ pointer.
Traits::Delete(reinterpret_cast<Type*>(subtle::NoBarrier_Load(&instance_)));
instance_ = 0;
}
static subtle::AtomicWord instance_;
}; template <typename Type, typename Traits, typename DifferentiatingType>
subtle::AtomicWord Singleton<Type, Traits, DifferentiatingType>::instance_ = 0; } // namespace base
也就是上图标红的一行,如下,
Type* newval = Traits::New();
单例创建完后,又是如何析构的呢,base::AtExitManager 帮我们做好了,看下面源码,
AtExitManager::~AtExitManager() {
if (!g_top_manager) {
NOTREACHED() << "Tried to ~AtExitManager without an AtExitManager";
return;
}
DCHECK_EQ(this, g_top_manager);
if (!g_disable_managers)
ProcessCallbacksNow();
g_top_manager = next_manager_;
}
// static
void AtExitManager::RegisterCallback(AtExitCallbackType func, void* param) {
DCHECK(func);
RegisterTask(base::Bind(func, param));
}
我们开头提到在 WinMain 函数中定义一个 AtExitManager 实例,程序结束后,栈上的内存自动释放,这时调用 AtExitManager 的析构函数释放使用 RegisterCallback 函数注册的回调函数
因为 base::Singleton 创建单例的时候自动注册了回调函数,见上面 base::Singleton 第二个标红处,如下,
AtExitManager::RegisterCallback(OnExit, NULL);
base::AtExitManager 内部会有一个链表维护这些实例,这样析构时也会逐个释放
一些有用的文章:
base::AtExitManager 和 base::Singleton 的结合使用的更多相关文章
- convert from base 10 to base 2
COMPUTER ORGANIZATION AND ARCHITECTURE DESIGNING FOR PERFORMANCE NINTH EDITION Hence, we convert fro ...
- Base系列编码浅析【base16 base32 base64 base85 base36 base 58 base91 base 92 base62】
Base系列编码浅析 [base16 base32 base64 base85 base36 base 58 base91 base 92 base62] base编码 ...
- 关于BASE 24 ,BASE 64原理以及实现程序
关于BASE 24 ,BASE 64原理以及实现程序 来源 https://wangye.org/blog/archives/5/ 可能很多人听说过Base64编码,很少有人听说过Base24编码,B ...
- ADS1.2中RO base与RW base
ARM映像文件 ARM中的各种源文件(包括汇编文件,C语言程序及C++程序等)经过ARM编译器编译后生成ELF(Executable and linking format)格式的目标文件.这些目标文件 ...
- int('x', base)中的base参数
>>> int('12', 16) 16表示'12'就是16进制数,int()要将这个16进制数转化成10进制.
- Appkiz.Base、Appkiz.Base.Languages
环境: ILSpy version 4.0.0.4319-beta2 选择 C#6.0 Visual Studio 2015 直接保存代码,直接用Visual Studio 2015打开.csprj文 ...
- Base 64 编码
原创地址:http://www.cnblogs.com/jfzhu/p/4020097.html 转载请注明出处 (一)Encoding VS. Encryption 很多人都以为编码(Encodin ...
- HTML/Elements/base
https://www.w3.org/wiki/HTML/Elements/base HTML/Elements/base < HTML | Elements List of Elemen ...
- The POM for XXX:jar:${com.ld.base.service.version} is missing, no dependency information available
最近有个jar改了名字后,有个依赖它的工程死活引用的是老名字,导致打包的时候出错,如下所示: [INFO] ---------------------------------------------- ...
- 封装常用的js(Base.js)——【01】理解库,获取节点,连缀,
封装常用的js(Base.js)——[01]理解库,获取节点,连缀, youjobit07 2014-10-10 15:32:59 前言: 现如今有太多优秀的开源javascript库, ...
随机推荐
- [转帖]从小白到精通:揭秘perf工具的全部功能与操作技巧
https://zhuanlan.zhihu.com/p/664396453 目录 收起 一.引言 二.理解perf工具的基本概念 三.安装与配置perf工具 3.1.不同操作系统的perf工具安 ...
- [转帖]Linux系统管理-crond、chkconfig、systemd、unit、target
https://cloud.tencent.com/developer/article/1409845 10.23 linux任务计划cron crontab命令被用来提交和管理用户的需要周期性执行的 ...
- [转帖]容器化 TCP Socket 缓存、接收窗口参数
https://blog.mygraphql.com/zh/notes/low-tec/network/tcp-mem/#rmem_default 最近需要支持一个单 POD 的 TCP 连接数上 1 ...
- [转帖]PostgreSQL 慢查询SQL跟踪
https://www.cnblogs.com/VicLiu/p/12017704.html PostgreSQL 开启慢SQL捕获在排查问题时是个很有效的手段.根据慢SQL让我在工作中真正解决了实际 ...
- [转帖]一文浅析Nginx线程池!
https://zhuanlan.zhihu.com/p/616500765 Nginx通过使用多路复用IO(如Linux的epoll.FreeBSD的kqueue等)技术很好的解决了c10k ...
- [转帖]Linux 监测服务心跳、服务重启策略
文章目录 前言 背景 一.curl服务可用验证 二.服务探测脚本 三.配置系统定时任务 四.Linux特殊字符转义 总结 前言 请各大网友尊重本人原创知识分享,谨记本人博客:南国以南i. 提示:以下是 ...
- [转帖]Linux开发环境——SCL软件集
一.SCL简介 1.SCL简介 SCL(Software Collections)是一个CentOS/RHEL Linux平台的软件多版本共存解决方案,为RHEL/CentOS Linux用户提供一 ...
- Oracle12c 快速启动命令设置
Oracle12c 安装完成之后 一般不会自动启动需要进行一下简单的设置才可以. 方法也比较简单. 可以使用 oracle 自带的 dbstart的命令执行服务启动 需要注意的事项是: 第一修改一个参 ...
- 基于Spring Cache实现Caffeine、jimDB多级缓存实战
作者: 京东零售 王震 背景 在早期参与涅槃氛围标签中台项目中,前台要求接口性能999要求50ms以下,通过设计Caffeine.ehcache堆外缓存.jimDB三级缓存,利用内存.堆外.jimDB ...
- vue 半场动画进入状态
<style> .box{ width: 30px; height: 30px; border-radius: 50%; background: red; } </style> ...