单例模式(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 的结合使用的更多相关文章

  1. convert from base 10 to base 2

    COMPUTER ORGANIZATION AND ARCHITECTURE DESIGNING FOR PERFORMANCE NINTH EDITION Hence, we convert fro ...

  2. 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编码 ...

  3. 关于BASE 24 ,BASE 64原理以及实现程序

    关于BASE 24 ,BASE 64原理以及实现程序 来源 https://wangye.org/blog/archives/5/ 可能很多人听说过Base64编码,很少有人听说过Base24编码,B ...

  4. ADS1.2中RO base与RW base

    ARM映像文件 ARM中的各种源文件(包括汇编文件,C语言程序及C++程序等)经过ARM编译器编译后生成ELF(Executable and linking format)格式的目标文件.这些目标文件 ...

  5. int('x', base)中的base参数

    >>> int('12', 16) 16表示'12'就是16进制数,int()要将这个16进制数转化成10进制.

  6. Appkiz.Base、Appkiz.Base.Languages

    环境: ILSpy version 4.0.0.4319-beta2 选择 C#6.0 Visual Studio 2015 直接保存代码,直接用Visual Studio 2015打开.csprj文 ...

  7. Base 64 编码

    原创地址:http://www.cnblogs.com/jfzhu/p/4020097.html 转载请注明出处 (一)Encoding VS. Encryption 很多人都以为编码(Encodin ...

  8. HTML/Elements/base

    https://www.w3.org/wiki/HTML/Elements/base HTML/Elements/base < HTML‎ | Elements   List of Elemen ...

  9. The POM for XXX:jar:${com.ld.base.service.version} is missing, no dependency information available

    最近有个jar改了名字后,有个依赖它的工程死活引用的是老名字,导致打包的时候出错,如下所示: [INFO] ---------------------------------------------- ...

  10. 封装常用的js(Base.js)——【01】理解库,获取节点,连缀,

    封装常用的js(Base.js)——[01]理解库,获取节点,连缀,  youjobit07 2014-10-10 15:32:59 前言:       现如今有太多优秀的开源javascript库, ...

随机推荐

  1. [转帖]rclone将本地文件或文件夹导入minio中

    1.背景:公司数据迁移涉及到文件迁移,原有文件服务器没有使用minio,但是现在的新系统使用了minio.所以这就需要我们将文件上传到minio文件服务器中:由于历史文件数据量大,甲方要求可以通过服务 ...

  2. [转帖]Jmeter学习笔记(十)——元件的作用域和执行顺序

    https://www.cnblogs.com/pachongshangdexuebi/p/11582891.html jmeter是一个开源的性能测试工具,它可以通过鼠标拖拽来随意改变元件之间的顺序 ...

  3. [转帖]谈 JVM 参数 GC 线程数 ParallelGCThreads 合理性设置

    https://my.oschina.net/u/4090830/blog/7926038 1. ParallelGCThreads 参数含义 在讲这个参数之前,先谈谈 JVM 垃圾回收 (GC) 算 ...

  4. es6新增的运算符-链判断运算符的诞生[?.]和null的判断运算符??

    指数运算符 ** console.log(2 ** 2 ) //4 console.log(2 ** 3 ) //8 console.log(2 ** 4) //16 链判断运算符的诞生(?.) 在实 ...

  5. vue中v-model修饰符的使用和组件使用v-model

    1.lazy 修饰器 lazy修饰器在input框中的表现效果是: 当你失去焦点后值才会跟新. 它的跟新时机是失去焦点后 这个修饰器在项目中运用的场景较少 <template> <d ...

  6. void的讲解 、any的讲解 、联合类型的讲解

    1. void的使用 空值一般采用 void 来表示,同时void也可以表示变量 也可以表示函数没有返回值哈 使用了 void 就不能够使用 return 哈 let sum = function() ...

  7. js下拉加载更多-详解

    场景 有些时候,我们在pc端经常会遇见滚动到底部的时候,去加载下一页的数据, 这个时候,我们就需要知道滚动条什么时候触底了, 如果触底了,就去加载下一页的数据; 在触底的过程中,我们需要注意的是,防止 ...

  8. [P9253 [PA 2022] Ornitolog 2] 题解

    题目 P9253 [PA 2022] Ornitolog 2 题目描述 给你一个长度为 \(n\) 的数列,求至少要修改多少个数才能让数列成为交替鹡鸰鸟鸣的音高序列. 思路 这道题有两种情况. 第一种 ...

  9. Go中sync.map使用小结

    sync.map 前言 深入了解下 查看下具体的实现 Load Store Delete LoadOrStore 总结 流程图片 参考 sync.map 前言 Go中的map不是并发安全的,在Go1. ...

  10. 分布式压测之locust和Jmeter的使用

    受限于单台机器的配置问题,我们在单台机器上达不到一个很高的压测并发数,那这个时候就需要引入分布式压测 分布式压测原理: 一般通过局域网把不同测试计算机链接到一起,达到测试共享.分散操作.集中管理的目的 ...