Re: Please disprove this Double-Checked Locking "fix"
On 2011-05-02 18:59:49 -0400, Joshua Maurice said:
What does change is when we throw std::atomic into the mix. When
pinstance is of type std::atomic, the following:
pinstance = new Singleton;
is equivalent to the following ala operator overloading pseudo-code
(forgive me for not knowing the specific function name offhand):
pinstance.set(new Singleton);
Let me say that more strongly. std::atomic<Singleton*> is a template
instantiation. It has an assignment operator that takes an argument of
type Singleton*. So in this code:
std::atomic<Singleton*> pinstance;
pinstance = new Singleton;
the assignment is implemented as a function call. All of the side
effects of evaluating the argument to the function call happen before
the call to the function, so the memory barrier that the assignment
establishes ensures that all of the side effects will be visible to
other threads before the assignment is visible.
That guarantee, though, depends on both the definition of the atomic
template and the new guarantees that compilers can't reorder
instructions across atomic operations.
--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)