brpc之单例

简介

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

GetLeakySingleton

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:创建实例的方法

初始化

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;

创建单例

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));
}

创建单例的模板方法

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);
}

相关推荐

  1. brpc

    2024-02-01 08:02:03       34 阅读
  2. brpcacceptor&&handler

    2024-02-01 08:02:03       11 阅读
  3. 【C++模式】

    2024-02-01 08:02:03       24 阅读
  4. QT模式

    2024-02-01 08:02:03       16 阅读
  5. 【前端设计模式】模式

    2024-02-01 08:02:03       42 阅读
  6. 【设计模式】模式

    2024-02-01 08:02:03       38 阅读
  7. C++设计模式模式

    2024-02-01 08:02:03       38 阅读
  8. 设计模式模式

    2024-02-01 08:02:03       37 阅读
  9. 设计模式模式

    2024-02-01 08:02:03       37 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-02-01 08:02:03       19 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-01 08:02:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-01 08:02:03       20 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-01 08:02:03       20 阅读

热门阅读

  1. Qt之connect函数使用

    2024-02-01 08:02:03       31 阅读
  2. 原型和继承

    2024-02-01 08:02:03       34 阅读
  3. electron从入门到打包exe

    2024-02-01 08:02:03       44 阅读
  4. 本地部署whisper模型(语音转文字)

    2024-02-01 08:02:03       36 阅读
  5. SummaryWriter函数用法

    2024-02-01 08:02:03       31 阅读
  6. Spring中用到的设计模式

    2024-02-01 08:02:03       31 阅读
  7. 实用Python定时点击Chrome网页按钮

    2024-02-01 08:02:03       37 阅读
  8. Vue之前端Broadcast Channel API的简单使用

    2024-02-01 08:02:03       41 阅读
  9. Day05-Linux bash核心介绍及目录命令讲解

    2024-02-01 08:02:03       37 阅读