C++ in Theory: Why the Double Check Lock Pattern Isn`t 100% Thread Safe
Back in January, Jun Nakamura discussed Singletons in a series of three articles, and revisited the subject in May. In the May article, he described the Double Checked Locking Pattern as a way to make Singletons thread safe. Unfortunately, it's not that simple, as he explains in this article.
C++ in Theory: Why the Double Check Lock Pattern Isn`t 100% Thread Safe - Portable Solutions (Page 6 of 6 )
At this point you will hopefully realize we are jumping through a lot of hoops, just to make sure we can construct a Singleton the lazy way. The simplest solution is to drop that requirement and initialize and destroy the Singleton in an orderly and controlled fashion. Are you having problems with the destruction sequence of Singletons after ‘at_exit()’ when your application is terminating? Stop being lazy and take control!
When you add a ‘Create()’ and ‘Destroy()’ function to your Singleton class and call these during your application’s initialization and destruction phases respectively, it will be much easier to control the multithreaded demon lurking in your code.
If this is not an option, another solution would be to use the mutex in the ‘Instance()’ function the expensive way, but to cache the pointer this function returns. This makes a lot of sense anyway, because dereferencing a pointer is cheaper than making a function call every time you need to have access to the Singleton.
Wow… that was quite a trip, trying to implement something that conceptually seemed so simple.
I would like to thank Scott Meyers for being so kind as to point out that the Double Checked Locked Pattern doesn’t make the Singleton 100 percent thread-safe.
‘Pattern Oriented Software Architectures Volume 2’ – ISBN 0471606952
‘Design Patterns’ – ISBN 0201633612
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.