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);
}
相关推荐
JosieBook1 小时前
【数据库】时序预测能力的分级进化:TimechoAI如何让每一类用户都能精准预见未来
java·开发语言·数据库
加号31 小时前
【C#】 文件与目录管理:创建、删除操作的技术解析
开发语言·c#
diving deep2 小时前
脚本速览-python
开发语言·python
一生了无挂2 小时前
Java处理JSON技巧教学(从基础到高阶实战全覆盖)
java·开发语言·json
swordbob2 小时前
Spring 单例 Bean 是线程安全的吗?
java·开发语言
小小编程路3 小时前
C++ 异常 完整讲解
开发语言·c++
AI科技星4 小时前
数术工坊 · 第四卷 橡皮泥江湖(拓扑学)【完整定稿】
c语言·开发语言·汇编·electron·概率论·拓扑学
张忠琳4 小时前
【Go 1.26.4】Golang Select 深度解析
开发语言·后端·golang
AC赳赳老秦5 小时前
OpenClaw+Power Apps 实战:自动生成 Power Apps 应用、连接 Excel 数据源
大数据·开发语言·python·serverless·excel·deepseek·openclaw
提笔了无痕5 小时前
如何用Go实现整套RAG流程
开发语言·后端·golang