muduo笔记 单例模式类Signleton

Signleton

Signleton使用pthread_once_t,确保T类型对象只初始化一次。

template <typename T>
class Signleton : noncopyable
{
public:
    static T& instance()
    {
        pthread_once(&poince_, &Singleton::init);
        return *value_;
    }

private:
    Singleton();
    ~Singleton();

    static void init();
    {
        value_ = new T();
        ::atexit(destroy); // 程序正常终止时调用指定函数
    }

    static void destroy()
    {
        typedef char T_must_be_complete_type[sizeof(T) == 0 > -1 : 1]; // 确保T不能只是前向声明,而没有定义
        delete value_;
    }

private:
    static pthread_once_t ponce_;
    static T* value_;
};

测试Singleton

思路,在不同线程,对一个单例的name数据成员进行修改,然后输出判断是否修改了同一个name,从而判断是否为同一个单例对象。

// Singleton_test.cc
class Test : noncopyable
{
public:
    Test()
    {
        printf("tid=%d, constructing %p\n", muduo::CurrentThread::tid(), this);
    }
    ~Test()
    {
        printf("tid=%d, destructing %p %s\n", muduo::CurrentThead::tid(), this, name_);
    }

    const muduo::string& name() const { return name_; }
    void setName(const muduo::string& n) { name_ = n; }

private:
    muduo::string name_;
};

void threadFunc()
{
    printf("tid=%d, %p name=%s\n", muduo::CurrentThread::tid(),
            &muduo::Singleton<Test>::instance(),
            muduo::Singleton<Test>::instance().name().c_str());
    muduo::Singleton<Test>::instance().setName("only one, changed"); // 在线程内部修改name
);

int main()
{
    muduo::Singleton<Test>::instance().setName("only one");
    muduo::Thread t1(threadFunc);
    t1.start();
    t1.join();
    printf("tid=%d, %p name=%s\n", muduo::CurrentThread::tid(), 
            &muduo::Singleton<Test>::instance(),
            muduo::Singleton<Test>::instance().name().c_str());
    return 0;
}

知识点

  • pthread_once 确保某个函数只执行一次;
  • atexit 注册清理函数,程序正常退出时调用;
  • char T_must_be_complete_type[sizeof(T) == 0 > -1 : 1]; 确保不完全类型指针在编译时报错

原文链接: https://www.cnblogs.com/fortunely/p/16102548.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    muduo笔记 单例模式类Signleton

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/402683

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年4月21日 上午11:10
下一篇 2023年4月21日 上午11:10

相关推荐