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);
}
相关推荐
MATLAB代码顾问12 小时前
MATLAB实现CNN(卷积神经网络)图像边缘识别
开发语言·matlab·cnn
FJW02081412 小时前
Python函数
开发语言·python
屁股割了还要学12 小时前
【C++进阶】STL-string的简单实现
c语言·开发语言·数据结构·c++·学习·考研
superlls12 小时前
(Java基础)集合框架继承体系
java·开发语言
ad钙奶长高高12 小时前
【C语言】原码反码补码详解
c语言·开发语言
IoT智慧学堂13 小时前
C语言运算符与表达式详解——算术、逻辑与赋值的全面理解
c语言·开发语言
沐知全栈开发13 小时前
深度优先遍历与连通分量
开发语言
古城小栈13 小时前
Go 1.25 发布:性能、工具与生态的全面进化
开发语言·后端·golang
@syh.14 小时前
【C++】map和set
开发语言·c++