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),这样就确保不会重复创建了。

  • 相关阅读:
    easyui中的combobox小知识点~~
    nodejs+express+mysql 增删改查
    建库和表的脚本.sql
    linux服务器最大连接数
    java高级主题
    java线程池ThreadPoolExecutor
    关于Future
    git rebase
    bash shell for循环
    accept()出的socket不会使用新的端口号
  • 原文地址:https://www.cnblogs.com/laohaozi/p/12537786.html
Copyright © 2011-2022 走看看