zoukankan      html  css  js  c++  java
  • 单例模式判断两次为NULL的原因

    单线程中:

    Singleton* getInstance()
    {
        if (instance == NULL)
            instance = new Singleton();
        return instance;
    }
    

    这样写可以保证只取得了一个实例。但是在多线程的环境下却不行了,因为很可能两个线程同时运行到if (instance == NULL)这一句,导致可能会产生两个实例。于是就要在代码中加锁。

    Singleton* getInstance()
    {
        lock();
        if (instance == NULL)
        {
           instance = new Singleton();
        }
        unlock();
        return instance;
    }
    

    但这样写的话,会稍稍映像性能,因为每次判断是否为空都需要被锁定,如果有很多线程的话,就爱会造成大量线程的阻塞。于是大神们又想出了双重锁定。

    Singleton* getInstance()
    {
        if (instance == NULL)
        {
    	lock();
        	if (instance == NULL)
        	{
           		instance = new Singleton();
        	}
        	unlock();
        }
    
        return instance;
    }
    

    写双重判断的原因如下
    在极低的几率下,通过if (instance == NULL)的线程才会有进入锁定临界区的可能性,这种几率还是比较低的,不会阻塞太多的线程,但为了防止一个线程进入临界区创建实例,另外的线程也进去临界区创建实例,又加上了一道防御if (instance == NULL),这样就确保不会重复创建了。

  • 相关阅读:
    JVM(二)JVM内存布局
    JVM(一) OpenJDK1.8源码在Ubuntu16.04下的编译
    阿里面试
    npm run dev/npm run start报错
    vue 项目报错 You may use special comments to disable some warnings.
    ES6模块化
    jQuery中的动画
    jsonp的封装
    ajax中get,post,以及二合一的封装
    小案例之刮奖
  • 原文地址:https://www.cnblogs.com/laohaozi/p/12537786.html
Copyright © 2011-2022 走看看