C++设计模式1:单例模式(懒汉模式和饿汉模式,以及多线程问题处理)

news/2024/9/23 7:33:17/

饿汉单例模式

        程序还没有主动获取实例对象,该对象就产生了,也就是程序刚开始运行,这个对象就已经初始化了。 

class Singleton
{
public:~Singleton(){std::cout << "~Singleton()" << std::endl;}static Singleton* get_instance(){return &singleton;}
private:Singleton() {};Singleton(const Singleton& othersingle) = delete;Singleton& operator=(const Singleton& othersingle) = delete;static Singleton singleton;
};
Singleton Singleton::singleton;//类的静态成员变量要在类外定义
int main()
{Singleton* s1 = Singleton::get_instance();Singleton* s2 = Singleton::get_instance();Singleton* s3 = Singleton::get_instance();std::cout << "s1:" << s1 << std::endl;std::cout << "s2:" << s2 << std::endl;std::cout << "s3:" << s3 << std::endl;
}

        显然饿汉模式是线程安全的,因为单例对象的初始化发生在.bss段,和栈无关,而线程的启动依赖于函数,函数需要开辟栈内存,所以是线程安全的。但是饿汉模式也有缺点,如果这个单例类的构造函数过于复杂,包含了线程和数据库等等一系列的初始化过程,需要进行大量操作,就会导致程序启动变慢。

运行结果如下:    三个对象的地址是一样的,说明是同一个对象,并且最后也只是析构了一次。

 懒汉模式

实例对象直到程序中有模块获取它时,才会初始化这个对象。

#include<iostream>
class Singleton
{
public:~Singleton(){std::cout << "~Singleton()" << std::endl;}static Singleton* get_instance(){if (singleton == nullptr){singleton = new Singleton();}return singleton;}
private:Singleton() {};Singleton(const Singleton& othersingle) = delete;Singleton& operator=(const Singleton& othersingle) = delete;static Singleton* singleton;
};
Singleton* Singleton::singleton=nullptr;//类的静态成员变量要在类外定义
int main()
{Singleton* s1 = Singleton::get_instance();Singleton* s2 = Singleton::get_instance();Singleton* s3 = Singleton::get_instance();std::cout << "s1:" << s1 << std::endl;std::cout << "s2:" << s2 << std::endl;std::cout << "s3:" << s3 << std::endl;
}

运行结果。 

         上面这种写法显然是线程不安全的,因为要构造一个单例,构造函数里面可能需要进行大量的操作。这段代码就会产生竞态条件,我们需要通过线程间的互斥操作来解决。

#include<iostream>
#include<memory>
#include<thread>
#include<mutex>
std::mutex mtx;
class Singleton
{
public:~Singleton(){std::cout << "~Singleton()" << std::endl;}static Singleton* get_instance(){std::lock_guard<std::mutex>loc(mtx);if (singleton == nullptr){singleton = new Singleton();}return singleton;}
private:Singleton() {};Singleton(const Singleton& othersingle) = delete;Singleton& operator=(const Singleton& othersingle) = delete;static Singleton* singleton;
};
Singleton* Singleton::singleton=nullptr;//类的静态成员变量要在类外定义
int main()
{Singleton* s1 = Singleton::get_instance();Singleton* s2 = Singleton::get_instance();Singleton* s3 = Singleton::get_instance();std::cout << "s1:" << s1 << std::endl;std::cout << "s2:" << s2 << std::endl;std::cout << "s3:" << s3 << std::endl;
}

         这种写法虽然可以解决问题,但是加锁的位置,对程序的性能损耗较大,每次要先拿到锁才去判断是否为nullptr,如果不是,这把锁就白拿了,换一下加锁的位置。

        

#include<iostream>
#include<memory>
#include<thread>
#include<mutex>
std::mutex mtx;
class Singleton
{
public:~Singleton(){std::cout << "~Singleton()" << std::endl;}static Singleton* get_instance(){if (singleton == nullptr){std::lock_guard<std::mutex>loc(mtx);singleton = new Singleton();}return singleton;}
private:Singleton() {};Singleton(const Singleton& othersingle) = delete;Singleton& operator=(const Singleton& othersingle) = delete;static Singleton* singleton;
};
Singleton* Singleton::singleton=nullptr;//类的静态成员变量要在类外定义
int main()
{Singleton* s1 = Singleton::get_instance();Singleton* s2 = Singleton::get_instance();Singleton* s3 = Singleton::get_instance();std::cout << "s1:" << s1 << std::endl;std::cout << "s2:" << s2 << std::endl;std::cout << "s3:" << s3 << std::endl;
}

        这次加锁位置明显可以减少程序的性能损耗,但是会出现一个问题,假如开始单例是nullptr,一个线程通过if语句,并且拿到了锁,它只是开辟了内存,并且构造了单例对象,但是构造过程没有执行完全,还没有给这个单例对象赋值, 这时候这个单例还是nullptr,另一个线程这时候也可以通过if语句了,因为单例是nullptr,但是它不能构造单例,因为没有拿到锁,这时候第一个线程给单例赋值完成后,释放了锁,第二个线程拿到锁,就又构造了一次单例。

        要解决这个问题也简单,那就是双重if语句判断。

#include<iostream>
#include<memory>
#include<thread>
#include<mutex>
std::mutex mtx;
class Singleton
{
public:~Singleton(){std::cout << "~Singleton()" << std::endl;}static Singleton* get_instance(){if (singleton == nullptr){std::lock_guard<std::mutex>loc(mtx);if (singleton == nullptr){singleton = new Singleton();}}return singleton;}
private:Singleton() {};Singleton(const Singleton& othersingle) = delete;Singleton& operator=(const Singleton& othersingle) = delete;static Singleton* singleton;
};
Singleton* Singleton::singleton=nullptr;//类的静态成员变量要在类外定义
int main()
{Singleton* s1 = Singleton::get_instance();Singleton* s2 = Singleton::get_instance();Singleton* s3 = Singleton::get_instance();std::cout << "s1:" << s1 << std::endl;std::cout << "s2:" << s2 << std::endl;std::cout << "s3:" << s3 << std::endl;
}

运行结果还是一样的。

        如果我们要简化上面的写法呢?我们可以使用到函数静态局部变量的初始化机制,函数静态局部变量在初始化的时候,底层的汇编指令会自动添加上线程互斥的指令,就可以省去我们加锁的步骤了。而且只有当程序主动调用get_instance函数的时候,单例才会被初始化,也省去了我们的nullptr双重判断了。

#include<iostream>
#include<memory>
#include<thread>
#include<mutex>
std::mutex mtx;
class Singleton
{
public:~Singleton(){std::cout << "~Singleton()" << std::endl;}static Singleton* get_instance(){static Singleton singleton;return &singleton;}
private:Singleton() {};Singleton(const Singleton& othersingle) = delete;Singleton& operator=(const Singleton& othersingle) = delete;static Singleton* singleton;
};
int main()
{Singleton* s1 = Singleton::get_instance();Singleton* s2 = Singleton::get_instance();Singleton* s3 = Singleton::get_instance();std::cout << "s1:" << s1 << std::endl;std::cout << "s2:" << s2 << std::endl;std::cout << "s3:" << s3 << std::endl;
}

运行效果一样。 


http://www.ppmy.cn/news/1514774.html

相关文章

设计模式 - 行为型模式(第六章)

目录 6、行为型模式 6.1 模板方法模式 6.1.1 概述 6.1.2 结构 6.1.3 案例实现 6.1.3 优缺点 6.1.4 适用场景 6.1.5 JDK源码解析 6.2 策略模式 6.2.1 概述 6.2.2 结构 6.2.3 案例实现 6.2.4 优缺点 6.2.5 使用场景 6.2.6 JDK源码解析 6.3 命令模式 6.3.1 概述 …

非关系型数据库MongoDB(文档型数据库)介绍与使用实例

MongoDB介绍 MongoDB是一种开源的文档型数据库管理系统&#xff0c;它使用类似于JSON的BSON格式&#xff08;Binary JSON&#xff09;来存储数据。与传统关系型数据库不同&#xff0c;MongoDB不使用表和行的结构&#xff0c;而是采用集合&#xff08;Collection&#xff09;(My…

鸿蒙内核源码分析(特殊进程篇)

三个进程 鸿蒙有三个特殊的进程&#xff0c;创建顺序如下: 2号进程&#xff0c;KProcess&#xff0c;为内核态根进程.启动过程中创建.0号进程&#xff0c;KIdle为内核态第二个进程&#xff0c;它是通过KProcess fork 而来的.这有点难理解.1号进程&#xff0c;init&#xff0c…

产品经理-​​实习中的自我迭代(41)

实习中的自我迭代,优秀实习生必备素质 跟大家认识了之后&#xff0c;就要开始做事情了&#xff0c;那我们怎么做一个优秀的实习生呢&#xff1f;以下几点作为参考。 1. 目标明确 知道自己的工作为什么要做&#xff0c;要做到什么程度&#xff0c;目前存在什么问题&#xff0c;该…

k8s上部署rancher

一、什么事rancher Rancher 是一个 Kubernetes 管理工具&#xff0c;让你能在任何地方和任何提供商上部署和运行集群。 Rancher 可以创建来自 Kubernetes 托管服务提供商的集群&#xff0c;创建节点并安装 Kubernetes&#xff0c;或者导入在任何地方运行的现有 Kubernetes 集…

Python中常见数据结构

文章目录 1. 列表&#xff08;List&#xff09;2. 元组&#xff08;Tuple&#xff09;3. 字典&#xff08;Dictionary&#xff09;4. 集合&#xff08;Set&#xff09;5. 数组&#xff08;Array&#xff09;6. 栈&#xff08;Stack&#xff09;7. 队列&#xff08;Queue&#x…

vue vite创建项目步骤

1. 创建vue项目 node版本需18以上 不然报错 npm init vuelatest2. 项目配置 配置项目的icon配置项目的标题配置jsconfig.json 3. 项目目录结构划分 4.css样式的重置 npm install normalize.cssreset.css html {line-height: 1.2; }body, h1, h2, h3, h4, ul, li {padding…

linux28学习 进程结束演示

signal.c #include <stdio.h> #include <signal.h> #include<unistd.h> void handler(int sig) { printf("catch a sig : %d\n", sig); } int main() { while(1){sleep(1);printf("进程号&#xff1a;%d\n",getpid());}return 0; }…