当前位置: 首页 > wzjs >正文

网站后台 教程株洲seo网络优化招聘网

网站后台 教程,株洲seo网络优化招聘网,织梦dedecms蓝色培训机构模板教育学校学院整站php网站源码,常州自助做网站简介 本文介绍C 线程安全的单例模式如何实现,通过介绍单例模式的演变历程,给读者更完备的实现单例模式的方案。 局部静态变量 我们知道当一个函数中定义一个局部静态变量,那么这个局部静态变量只会初始化一次,就是在这个函数第…

简介

本文介绍C++ 线程安全的单例模式如何实现,通过介绍单例模式的演变历程,给读者更完备的实现单例模式的方案。

局部静态变量

  • 我们知道当一个函数中定义一个局部静态变量,那么这个局部静态变量只会初始化一次,就是在这个函数第一次调用的时候,以后无论调用几次这个函数,函数内的局部静态变量都不再初始化。那我们可以利用局部静态变量这一特点实现单例

class Single2 {
private:Single2(){}Single2(const Single2&) = delete;Single2& operator=(const Single2&) = delete;
public:static Single2& GetInst(){static Single2 single;return single;}
};
  • 上述版本的单例模式在C++11 以前存在多线程不安全的情况,编译器可能会初始化多个静态变量。
    但是C++11推出以后,各厂商优化编译器,能保证线程安全。所以为了保证运行安全请确保使用C++11以上的标准。
    在这里插入图片描述

  • 注意下面的介绍都是C++11标准11以前单例模式的演变历程,C++11以后就直接写成上面哪个就OK,因为C++11要求各厂商必须在多线程的情况下保证静态变量初始化的安全性

饿汉式初始化

  • 在C++11 推出以前,局部静态变量的方式实现单例存在线程安全问题,所以部分人推出了一种方案,就是在主线程启动后,其他线程没有启动前,由主线程先初始化单例资源,这样其他线程获取的资源就不涉及重复初始化的情况了。

#include<iostream>
#include<algorithm>
#include<mutex>
#include<thread>
using std::cout;
using std::endl;// 饿汉式
class Single2Hungry
{
private:Single2Hungry(){}Single2Hungry(const Single2Hungry&) = delete;Single2Hungry& operator=(const Single2Hungry&) = delete;
public:static Single2Hungry* GetInst(){if (single == nullptr){single = new Single2Hungry();}return single;}
private:static Single2Hungry* single;
};
//饿汉式初始化
Single2Hungry* Single2Hungry::single = Single2Hungry::GetInst();
void thread_func_s2(int i)
{std::cout << "this is thread " << i << std::endl;std::cout << "inst is " << Single2Hungry::GetInst() << std::endl;
}
void test_single2hungry()
{std::cout << "s1 addr is " << Single2Hungry::GetInst() << std::endl;std::cout << "s2 addr is " << Single2Hungry::GetInst() << std::endl;for (int i = 0; i < 3; i++){std::thread tid(thread_func_s2, i);tid.join();}
}
  • 饿汉式是从使用角度规避多线程的安全问题,很多情况下我们很难从规则角度限制开发人员,所以这种方式不是很推荐。

懒汉式初始化

  • 很多人觉得什么时候调用初始化是用户的权利,不应该加以限制,所以就有了懒汉式方式初始化资源,在用到时如果没有初始化单例则初始化,如果初始化了则直接使用.

  • 所以这种方式我们要加锁,防止资源被重复初始化。

#include<iostream>
#include<algorithm>
#include<mutex>
#include<thread>
using std::cout;
using std::endl;class SinglePointer
{
private:SinglePointer(){}SinglePointer(const SinglePointer&) = delete;SinglePointer& operator=(const SinglePointer&) = delete;
public:static SinglePointer* GetInst(){if (single != nullptr){return single;}//s_mutex.lock();if (single != nullptr){s_mutex.unlock();return single;}single = new SinglePointer();s_mutex.unlock();return single;}
private:static SinglePointer* single;static std::mutex s_mutex;
};
  • 懒汉式二次检查的必要性

在这里插入图片描述

  • 这种方式存在一个很严重的问题,就是当多个线程都调用单例函数时,我们不确定资源是被哪个线程初始化的。回收指针存在问题,存在多重释放或者不知道哪个指针释放的问题。

智能指针

我们能想到一个自动初始化资源并且自动释放的方式就是智能指针。利用智能指针自动回收资源。

#include<iostream>
#include<algorithm>
#include<mutex>
#include<thread>
using std::cout;
using std::endl;//可以利用智能指针完成自动回收
class SingleAuto
{
private:SingleAuto(){}SingleAuto(const SingleAuto&) = delete;SingleAuto& operator=(const SingleAuto&) = delete;
public:~SingleAuto(){std::cout << "single auto delete success " << std::endl;}static std::shared_ptr<SingleAuto> GetInst(){if (single != nullptr){return single;}s_mutex.lock();if (single != nullptr){s_mutex.unlock();return single;}single = std::shared_ptr<SingleAuto>(new SingleAuto);s_mutex.unlock();return single;}
private:static std::shared_ptr<SingleAuto> single;static std::mutex s_mutex;
};std::shared_ptr<SingleAuto> SingleAuto::single = nullptr;
std::mutex SingleAuto::s_mutex;
void test_singleauto()
{auto sp1 = SingleAuto::GetInst();auto sp2 = SingleAuto::GetInst();std::cout << "sp1  is  " << sp1 << std::endl;std::cout << "sp2  is  " << sp2 << std::endl;//此时存在隐患,可以手动删除裸指针,造成崩溃// delete sp1.get();
}

这样开辟的资源交给智能指针管理免去了回收资源的麻烦。
但是有些人觉得虽然智能指针能自动回收内存,如果有开发人员手动delete指针怎么办?
所以有人提出了利用辅助类帮助智能指针释放资源,将智能指针的析构设置为私有。


#include<iostream>
#include<algorithm>
#include<mutex>
#include<thread>
using std::cout;
using std::endl;//为了规避用户手动释放内存,可以提供一个辅助类帮忙回收内存
//并将单例类的析构函数写为私有
class SingleAutoSafe;
class SafeDeletor
{
public:void operator()(SingleAutoSafe* sf){std::cout << "this is safe deleter operator()" << std::endl;delete sf;}
};class SingleAutoSafe
{
private:SingleAutoSafe() {}~SingleAutoSafe(){std::cout << "this is single auto safe deletor" << std::endl;}SingleAutoSafe(const SingleAutoSafe&) = delete;SingleAutoSafe& operator=(const SingleAutoSafe&) = delete;//定义友元类,通过友元类调用该类析构函数friend class SafeDeletor;
public:static std::shared_ptr<SingleAutoSafe> GetInst(){//1处if (single != nullptr){return single;}s_mutex.lock();//2处if (single != nullptr){s_mutex.unlock();return single;}//额外指定删除器  //3 处single = std::shared_ptr<SingleAutoSafe>(new SingleAutoSafe, SafeDeletor());//也可以指定删除函数// single = std::shared_ptr<SingleAutoSafe>(new SingleAutoSafe, SafeDelFunc);s_mutex.unlock();return single;}
private:static std::shared_ptr<SingleAutoSafe> single;static std::mutex s_mutex;
};
  • SafeDeletor就是删除的辅助类,实现了仿函数。构造智能指针时指定了SafeDeletor对象,这样就能帮助智能指针释放了。
    在这里插入图片描述

call_once

  • C++11 提出了call_once函数,我们可以配合一个局部的静态变量once_flag实现线程安全的初始化。多线程调用call_once函数时,会判断once_flag是否被初始化,如没被初始化则进入初始化流程,调用我们提供的初始化函数。但是同一时刻只有一个线程能进入这个初始化函数。

#include<iostream>
#include<algorithm>
#include<mutex>
#include<thread>
using std::cout;
using std::endl;class SingletonOnce 
{
private:SingletonOnce() = default;SingletonOnce(const SingletonOnce&) = delete;SingletonOnce& operator = (const SingletonOnce& st) = delete;static std::shared_ptr<SingletonOnce> _instance;
public:static std::shared_ptr<SingletonOnce> GetInstance() {static std::once_flag s_flag;std::call_once(s_flag, [&]() {_instance = std::shared_ptr<SingletonOnce>(new SingletonOnce);});return _instance;}void PrintAddress() {std::cout << _instance.get() << std::endl;}~SingletonOnce() {std::cout << "this is singleton destruct" << std::endl;}
};
std::shared_ptr<SingletonOnce> SingletonOnce::_instance = nullptr;void TestSingle() {std::thread t1([]() {std::this_thread::sleep_for(std::chrono::seconds(1));SingletonOnce::GetInstance()->PrintAddress();});std::thread t2([]() {std::this_thread::sleep_for(std::chrono::seconds(1));SingletonOnce::GetInstance()->PrintAddress();});t1.join();t2.join();
}
  • 为了使用单例类更通用,比如项目中使用多个单例类,可以通过继承实现多个单例类

#include<iostream>
#include<algorithm>
#include<mutex>
#include<thread>
using std::cout;
using std::endl;//为了让单例更加通用,可以做成模板类
template <typename T>
class Singleton {
protected:Singleton() = default;Singleton(const Singleton<T>&) = delete;Singleton& operator=(const Singleton<T>& st) = delete;static std::shared_ptr<T> _instance;
public:static std::shared_ptr<T> GetInstance() {static std::once_flag s_flag;std::call_once(s_flag, [&]() {_instance = std::shared_ptr<T>(new T);});return _instance;}void PrintAddress() {std::cout << _instance.get() << std::endl;}~Singleton() {std::cout << "this is singleton destruct" << std::endl;}
};
template <typename T>
std::shared_ptr<T> Singleton<T>::_instance = nullptr;
  • 比如我们想实现单例类,就像我们之前在网络编程中介绍的那样,可以通过继承实现单例模式

//想使用单例类,可以继承上面的模板,我们在网络编程中逻辑单例类用的就是这种方式
class LogicSystem :public Singleton<LogicSystem>
{friend class Singleton<LogicSystem>;
public:~LogicSystem(){}
private:LogicSystem(){}
};

总结


文章转载自:

http://zZxEpJDe.nmfxs.cn
http://UxPuXt74.nmfxs.cn
http://jhtvVAwh.nmfxs.cn
http://Y4qqS4dF.nmfxs.cn
http://qRhbiRjT.nmfxs.cn
http://LVC29Wzo.nmfxs.cn
http://PcIENv4G.nmfxs.cn
http://UGE9kxFU.nmfxs.cn
http://gpKsAeXa.nmfxs.cn
http://tAILbLIc.nmfxs.cn
http://VMD02LSz.nmfxs.cn
http://tVL87zDU.nmfxs.cn
http://xTSdLRJi.nmfxs.cn
http://KYlCxJQf.nmfxs.cn
http://lF16JKCc.nmfxs.cn
http://gZCebApn.nmfxs.cn
http://VuLhlPv9.nmfxs.cn
http://CRnaEdQl.nmfxs.cn
http://4qTnDJbQ.nmfxs.cn
http://pbZqWSg1.nmfxs.cn
http://omPNRdz2.nmfxs.cn
http://cbrXLy1m.nmfxs.cn
http://1XnhQhJM.nmfxs.cn
http://JM65sxj0.nmfxs.cn
http://diK7U3o4.nmfxs.cn
http://5oT0G8gE.nmfxs.cn
http://rDf6UjKP.nmfxs.cn
http://gY3oB8qe.nmfxs.cn
http://lc64WJUW.nmfxs.cn
http://42GFaOPs.nmfxs.cn
http://www.dtcms.com/wzjs/643196.html

相关文章:

  • 深圳网站建设公司收费石家庄制作网站的公司
  • wap网站psd网站的修改建设文字
  • 绍兴网站建设电话加强网站及微信平台建设
  • dw里面怎么做网站轮播图北京网站制作公司招聘信息
  • 网站规划的意义中国互联网设计公司
  • php网站开发结构说明360网站 备案
  • 沈阳开发网站公司网站建设的发展趋势
  • 外围网站开发推广app大全
  • 做景观的网站学院网站建设策划书
  • 小俊哥网站建设怎样做淘宝联盟的网站
  • 网站建设常见问题解决方案wordpress论坛模板
  • 做网站什么空间好做英文企业网站
  • 合肥网站建设排名wordpress 显示excel
  • 网站怎么做第三方支付接口手机网站开发和pc网站的区别
  • 网站做动态虚线discuz应用中心破解
  • 织梦网站流动广告代码做公众号可以看的网站
  • 求个没封的w站2022简单的企业网站
  • 带后台的网站建设学校网站查询个人信息
  • 济南做网站优化深圳私人网站优化
  • 网站备案要关闭吗atp最新排名
  • 自己人网站建设e龙岩官网下载电脑版
  • 开个小网站要怎么做的盘锦做网站建设的
  • 企业网站设计分类wordpress收费下载模板
  • 做php网站用什么软件wordpress安装语言设置
  • 滑县做网站一级a做爰片i网站
  • 网站建设价格方案wordpress 页面显示分类文章列表
  • 系统网站开发宜宾三江新区核酸检测
  • 网站开发和推广方案亿网通官网
  • 商家建设网站的好处建网站用的域名多少钱
  • 三点水网站建设proe设计实例100例