brpc之单例

简介

GetLeakySingleton是单例模板类,线程安全的

GetLeakySingleton

cpp 复制代码
template <typename T> class GetLeakySingleton {
public:
    static butil::subtle::AtomicWord g_leaky_singleton_untyped;
    static pthread_once_t g_create_leaky_singleton_once;
    static void create_leaky_singleton();
};

包含三个静态成员

g_leaky_singleton_untyped:存放分配后的地址

g_create_leaky_singleton_once:创建时保证只调用一次

create_leaky_singleton:创建实例的方法

初始化

cpp 复制代码
template <typename T>
butil::subtle::AtomicWord GetLeakySingleton<T>::g_leaky_singleton_untyped = 0;

template <typename T>
pthread_once_t GetLeakySingleton<T>::g_create_leaky_singleton_once = PTHREAD_ONCE_INIT;

创建单例

cpp 复制代码
template <typename T>
void GetLeakySingleton<T>::create_leaky_singleton() {
    T* obj = new T;
    butil::subtle::Release_Store(
        &g_leaky_singleton_untyped,
        reinterpret_cast<butil::subtle::AtomicWord>(obj));
}

创建单例的模板方法

cpp 复制代码
template <typename T>
inline T* get_leaky_singleton() {
    const butil::subtle::AtomicWord value = butil::subtle::Acquire_Load(
        &GetLeakySingleton<T>::g_leaky_singleton_untyped);
    if (value) {
        return reinterpret_cast<T*>(value);
    }
    pthread_once(&GetLeakySingleton<T>::g_create_leaky_singleton_once,
                 GetLeakySingleton<T>::create_leaky_singleton);
    return reinterpret_cast<T*>(
        GetLeakySingleton<T>::g_leaky_singleton_untyped);
}
相关推荐
海的诗篇_2 分钟前
前端开发面试题总结-JavaScript篇(一)
开发语言·前端·javascript·学习·面试
じ☆ve 清风°12 分钟前
理解JavaScript中map和parseInt的陷阱:一个常见的面试题解析
开发语言·javascript·ecmascript
sss191s24 分钟前
Java 集合面试题从数据结构到 HashMap 源码剖析详解及常见考点梳理
java·开发语言·数据结构
IGP929 分钟前
20250606-C#知识:委托和事件
开发语言·c#
hjyowl39 分钟前
题解:AT_abc407_c [ABC407C] Security 2
c语言·开发语言·算法
唐墨12341 分钟前
android与Qt类比
android·开发语言·qt
Code_流苏1 小时前
C++课设:简易日历程序(支持传统节假日 + 二十四节气 + 个人纪念日管理)
开发语言·c++·stl容器·课设·期末大作业·日历程序·面向对象设计
道剑剑非道2 小时前
QT开发技术【ffmpeg + QAudioOutput】音乐播放器 完善
开发语言·qt·ffmpeg
武昌库里写JAVA2 小时前
iview Switch Tabs TabPane 使用提示Maximum call stack size exceeded堆栈溢出
java·开发语言·spring boot·学习·课程设计
lexiangqicheng2 小时前
JS-- for...in和for...of
开发语言·前端·javascript