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);
}
相关推荐
隐积13 小时前
3.1.7.Qt容器大家族(3):QVariant——万能盒子
开发语言·qt
名字还没想好☜16 小时前
Next.js ‘use client‘ 到底加在哪:Server/Client Components 边界与常见报错
开发语言·前端·javascript·react·next.js
初级代码游戏17 小时前
iOS开发 Swift 速记1:变量和基本数据类型
开发语言·ios·swift
酷在前行18 小时前
【R生态】PERMANOVA 进阶实战:距离选择、PERMDISP、两两比较与受限置换(保姆级教程)
开发语言·r语言
cxr82818 小时前
Graphify vs GitNexus vs CodeGraph — 三工具架构深度对比
开发语言·架构·知识图谱
废弃的小码农19 小时前
功能测试--Day07--Python编程基础
开发语言·python
fengci.20 小时前
Microweber CMS 未授权路径穿越漏洞(CVE-2026-65694)
android·开发语言·前端·学习·php
程序员zgh20 小时前
C++ 拷贝赋值运算符 详解
c语言·开发语言·c++
念何架构之路20 小时前
restartmanager-重启管理子系统
java·开发语言
SomeB1oody21 小时前
【RustyML入门】2.0. 经典机器学习
开发语言·后端·机器学习·rust·教程