C++ in Theory: Why the Double Check Lock Pattern Isn`t 100% Thread Safe
(Page 1 of 6 )
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.
If you wish to catch up with the articles from January covering the Singleton, you may do so here:
The Double Checked Locking Pattern looks like a simple way to ensure that we can make Singletons thread safe. While the simplest solution is often the best, this one contains complexities underneath that don’t show until you take a closer look...a much closer look.
C++ as a language has no notion of threading. Unfortunately, this makes it possible for compilers to break our programs in the most unexpected ways!
As if matters are not complex enough when trying to write thread-safe C++ code, we should also think hard about the machine code a compiler may actually generate from our C++ code. We must always try to be very vigilant. Sometimes, we’ll get lucky and have someone point out what we might have missed.
In my case Scott Meyers [Meyers] was kind enough to point out that the Double-Checked Locking Pattern [Schmidt/Harrison] described in my previous article "The Singleton Pattern Revisited" is not reliable in C++. I suggest you read the excellent article he and Andrei Alexandrescu wrote on this topic at http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004.pdf for a thorough explanation. I will merely summarize the problem here for you.
Next: The Original Problem >>
More C++ Articles
More By J. Nakamura