单例模式(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. [转帖]一图胜千言 -- SQL Server 基准测试

    https://blog.51cto.com/ultrasql/2130487 文章标签基准测试文章分类SQL Server数据库阅读数1116  

  2. [转帖]分享6个SQL小技巧

    https://www.jianshu.com/p/2fcf0a4e83b7   简介 经常有小哥发出疑问,SQL还能这么写?我经常笑着回应,SQL确实可以这么写.其实SQL学起来简单,用起来也简单, ...

  3. [转帖]tidb-lightning 逻辑模式导入

    https://docs.pingcap.com/zh/tidb/stable/tidb-lightning-configuration 本文档介绍如何编写逻辑导入模式的配置文件,如何进行性能调优等内 ...

  4. [转帖]Linux中awk命令正确的求最大值、最小值、平均值、总和

    https://blog.csdn.net/fireblue1990/article/details/51622416 test.txt文件内容: 9 11 35 21 42 118 求最大值: aw ...

  5. [转帖]exec系统调用

    https://www.jianshu.com/p/3bf14f7d889c 进程的执行(exec) execve ececve系统调用可以将新程序加载到调用进程的内存空间,在这一过程中,将丢弃现有的 ...

  6. [转帖]kubernetes Flannel网络剖析

    https://plantegg.github.io/2022/01/19/kubernetes_Flannel%E7%BD%91%E7%BB%9C%E5%89%96%E6%9E%90/ cni(Co ...

  7. miniIO系列文章03---abpvext中集成

    在Abp商业版本中已经提供了文件管理模块的,免费版本是没有的,本文将介绍如何使用Minio打造一个自己的文件管理模块. 在项目开始之前,需要先安装一个Minio服务,可以在本地pc或云主机中安装,具体 ...

  8. 情侣纪念日网站html5源码教程

    个人名片: 对人间的热爱与歌颂,可抵岁月冗长 Github‍:念舒_C.ying CSDN主页️:念舒_C.ying 个人博客 :念舒_C.ying 预览图 直接进入我的网站吧 >> Z_ ...

  9. 从零开始配置 vim(12)——主题配置

    在我们进一步增强vim的功能之前,我们先为vim准备一个漂亮的主题,毕竟对着一个丑陋原始的界面多少有点提不起劲来进行编程.长时间对着丑陋的界面多多少少会产生抑郁情绪的.下面推荐几款我觉得还不错的主题插 ...

  10. MySQL 中使用变量实现排名名次

    title: MySQL 中使用变量实现排名名次 date: 2023-7-16 19:45:26 tags: - SQL 高级查询 一. 数据准备: CREATE TABLE sql_rank ( ...