Search⌘ K

Double-Checked Locking Pattern

Explore the double-checked locking pattern used for thread-safe singleton initialization and understand why it fails under modern C++ memory models. Learn about the performance trade-offs and the reasons behind potential undefined behavior caused by instruction reordering in concurrent environments.

We'll cover the following...

The double-checked locking pattern is the classic way to initialize a singleton in a thread-safe way. What sounds like established best practice - or a pattern - is more a kind of an anti-pattern. It assumes guarantees in the classical implementation, which aren’t given by the Java, C#, or C++ memory model. The wrong assumption is that the creation of a singleton is an atomic operation; therefore, a solution that seems to be thread-safe is not thread-safe.

What is the double-checked locking pattern? The first ...