Sep 5, 2011

[C++]Double-Checked Locking Pattern

Double-Checked Locking Pattern


Paper:
C++ and the Perils of Double-Checked Locking



ensuring that the machine instructions executed during DCLP are executed in an acceptable order.

IamClass Foo = new IamClass() causes three things to happen:
      Allocate memory to hold a Singleton object.
      Construct a Singleton object in the allocated memory.
      Make pInstance point to the allocated memory.
Of critical importance is the observation that compilers are not constrained
to perform these steps in this order! In particular, compilers are sometimes
allowed to swap steps 2 and 3. Why they might want to do that is a question
we’ll address in a moment. For now, let’s focus on what happens if they do.
const-qualified objects don’t become const until their constructors
have run to completion, volatile-qualified objects become volatile
only upon exit from their constructors.

DCLP on Multiprocessor Machines:
Suppose you’re on a machine with multiple processors, each of which has its
own memory cache, but all of which share a common memory space. Such an
architecture needs to define exactly how and when writes performed by one
processor propagate to the shared memory and thus become visible to other
processors. It is easy to imagine situations where one processor has updated
the value of a shared variable in its own cache, but the updated value has not
yet been flushed to main memory, much less loaded into the other processors’
caches. Such inter-cache inconsistencies in the value of a shared variable is
known as the cache coherency problem.
In many cases, initializing a singleton resource during single-threaded program startup
(e.g., prior to executing main) is the simplest way to offer fast, thread-safe
singleton access.



Reference:
Discussion on C++.Moderated
volatile (C++)
Memory barrier
LINUX KERNEL MEMORY BARRIERS
[C++0x] std::atomic class template
[comp.lang.c++.moderated]Double checked locking pattern article on aristeia

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.