Original address
Http://www.cnblogs.com/hebaichuanyeah/p/6298513.html
A typical singleton pattern building object's double check lock is as follows:
Static Singleton * getsingleobject () { if(singleobject==NULL) { lock (); if (singleobject==NULL) { new Singleton (); } Unlock (); } return singleobject; }
The logic of the code is that the Getsingleobject () function obtains the object, creates it if the object does not exist, and then returns directly. With thread safety in mind, it is necessary to lock the object when it is created (otherwise multiple objects may be created when the function is called at the same time). At the same time, in order to avoid the thread each time calls Getsingleobject () function to be locked waiting, reduce the overhead between threads, using double check lock, that is, only the object does not exist to lock the wait.
Looks flawless ...
When C + + is in the new object, the pointer is first pointed to the allocated space, and then the space is initialized.
This assumes that when thread a executes to new, the pointer is assigned, but the space has not yet been built. At this point, thread B executes the getsingleobject () function, because the pointer is already assigned so it returns the address directly (but it is actually an uninitialized address), and thread B operates the address, game over.
Zatan C + + Double check lock is not secure