Singleton Pattern Part 3 | Design Pattern

Double Checked Locking Pattern

// implementation of getInstance() method
Singleton* Singleton::pInstance = 0;
Singleton* Singleton::getInstance()
{
    if (pInstance == 0) {
        Lock lock; //acquire Lock (actual syntax may differ)
        if (pInstance == 0) {
            pInstance = new Singleton;
        }
        Unlock lock; //release lock
    }
    return pInstance;
}

In DCLP we check pInstance NULL check before acquiring Lock. Only if the test succeeds (i.e., if pInstance has not yet been initialized) is the lock acquired, and after that the test is performed again to make sure pInstance is still null (hence the name double-checked locking).
The second test is necessary ,as it is possible that another thread may initialize pInstance between the time pInstance was first tested and the time the lock was acquired.

DCLP may work most of the time but DCLP does not guarantee that it works every time in multi-thread environment.This is because machine instruction executed during DCLP may occur in different order in different time. Lets discuss this in detail.

Site Footer