文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>An essay about double-check

An essay about double-check

时间:2010-03-27  来源:qytan36

An essay about double-check

     In some situations, we often use singleton pattern to ensure only one instance of the object would be created in our system. The code is often like this: 

class Singleton
{
private:
    static Singleton *instance;

public:
    static Singleton* getInstance();

private:
    Singleton();//declare the constructor to be private in order to avoid to be called by others.

};

 

Singleton *Singleton::instance = NULL;

//v1:

Singleton* Singleton::getInstance()
{
    if(NULL == instance) //check statement

    {
        //object production block

        instance = new Singleton();
    }
    return instance;
}

Singleton::Singleton()
{
    //initializing...

}


 However, if Singleton::getInstance() is accessed by multiple threads simultaneously, maybe one thread is interrupted just after it passes the check statement, then another thread could enter the object production block too, so the object may be created twice or more times. In this case, there would be more than one object instances in our system, which obeys the idea of singleton factory. To keep the object production block as a crucial area, we could introduce a mutex. Like this:

//v2:

Singleton* Singleton::getInstance()

{

    lock(mutex); //the implemntation of mutex and releated operations vary on differnt platforms.

    if(NULL == instance) //check statement

    {

        //object production block

        instance = new Singleton();

    }

    release(mutex);
    return instance;
}


Now it seems safe enough to ensure only one thread could enter the object production block. It's ture. But the performance issue comes out as a pair of mutex lock and realease operations needs to be executed every time Singleton::getInstance() is called. In fact, after the first call, the instance won't be NULL. So the cost is really very expensive. Don't worry, double-check is designed to solve this problem very well.

 

//v3:


Singleton* Singleton::getInstance()

{

     if(NULL == instance)

     {

        //After the creation of the object once, no thread would enter this block any more, thus the performance is as good as v1 and the secuity is as good as v2.


        //perfect, isn't it.


        lock(mutex);

        if(NULL == instance) //check statement


        {

            //object production block


            instance = new Singleton();

        }

        release(mutex);

     }

    return instance;

}


相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载