懒汉模式在第一次用到类实例的时候才会去实例化,就是不到调用getInstance函数时,这个类的对象是一直不存在的。懒汉本身是线程不安全的。
#include <iostream>using namespace std;class Singelton{private: Singelton(){ m_count ++; printf("Singelton begin\n"); Sleep(1000);// 加sleep为了放大效果 printf("Singelton end\n"); } static Singelton *single;//定义一个唯一指向实例的指针,并且是私有的public: static Singelton *GetSingelton();//定义一个公有函数,可以获取这个唯一实例 static void print(); static int m_count;}; //将唯一指向实例的指针初始化为nullptrSingelton *Singelton::single = nullptr;int Singelton::m_count = 0;Singelton *Singelton::GetSingelton(){ if(single == nullptr){//判断是不是第一次使用 single = new Singelton; } return single;}void Singelton::print(){ cout<<m_count<<endl;}int main(){ singleton* a1 = singleton::GetInstance(); cout << a1 << endl; a1->print(); singleton* a2 = singleton::GetInstance(); cout << a2 << endl; a2->print(); system("pause"); return 0;}
懒汉模式的singleton类有以下特点:
1.他有一个指向唯一实例的静态指针,并且是私有的。
2.它有一个公有的函数,可以获取这个唯一的实例,并且在需要的时候创建该实例。
3.它的构造函数是私有的,这样就不能从别处创建该类的实例。
饿汉模式在单例类定义的时候(即在main函数之前)就进行实例化。因为main函数执行之前,全局作用域的类成员静态变量m_Instance已经初始化,故没有多线程的问题。
#include <iostream>#include <process.h>#include <windows.h>using namespace std;class Singelton{private: Singelton(){ m_count ++; printf("Singelton begin\n"); Sleep(1000); // 加sleep为了放大效果 printf("Singelton end\n"); } static Singelton *single;//定义一个唯一指向实例的指针,并且是私有的public: static Singelton *GetSingelton();//定义一个公有函数,可以获取这个唯一实例 static void print(); static int m_count;};// 饿汉模式的关键:定义即实例化Singelton *Singelton::single = new Singelton;int Singelton::m_count = 0;Singelton *Singelton::GetSingelton(){ // 不再需要进行实例化 //if(single == nullptr){ // single = new Singelton; //} return single;}void Singelton::print(){ cout<<m_count<<endl;}int main(){ cout << "we get the instance" << endl; singleton* a1 = singleton::getinstance(); singleton* a2 = singleton::getinstance(); singleton* a3 = singleton::getinstance(); cout << "we destroy the instance" << endl; system("pause"); return 0;}
在多线程环境下,懒汉模式的上述实现方式是不安全的,原因在于在判断instance是否为空时,可能存在多个线程同时进入if中,此时可能会实例化多个对象。于是出现了二重锁的懒汉模式,实现代码如下:
#include<iostream>#include<mutex>using namespace std;/*单例模式:构造函数私有化,对外提供一个接口*///线程安全的单例模式class lhsingleClass {public: static lhsingleClass* getinstance() {//双重锁模式 if (instance == nullptr) {//先判断是否为空,如果为空则进入,不为空说明已经存在实例,直接返回 //进入后加锁 i_mutex.lock(); if (instance == nullptr) {//再判断一次,确保不会因为加锁期间多个线程同时进入 instance = new lhsingleClass(); } i_mutex.unlock();//解锁 } return instance; }private: static lhsingleClass* instance; static mutex i_mutex;//锁 lhsingleClass(){}};lhsingleClass* lhsingleClass::instance=nullptr;mutex lhsingleClass::i_mutex;//类外初始化 int main(){ lhsingleClass* lhsinglep5 = lhsingleClass::getinstance(); lhsingleClass* lhsinglep6 = lhsingleClass::getinstance(); cout << lhsinglep5 << endl; cout << lhsinglep6 << endl; system("pause"); return 0;}
此代码共进行了两次判断:
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注w3xue的更多内容!
本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728