C++ and the Perils of Double-Checked Locking

http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf


C++ and the Perils of Double-Checked Locking ∗

Scott Meyers and Andrei Alexandrescu
September 2004
Multithreading is just one damn thing after, before, or simultaneous
with another.
1 Introduction
Google the newsgroups or the web for the names of various design patterns,
and you’re sure to find that one of the most commonly mentioned is Singleton.
Try to put Singleton into practice, however, and you’re all but certain to bump
into a significant limitation: as traditionally implemented (and as we explain
below), Singleton isn’t thread-safe.
Much effort has been put into addressing this shortcoming. One of the most
popular approaches is a design pattern in its own right, the Double-Checked
Locking Pattern (DCLP) [13, 14]. DCLP is designed to add efficient threadsafety
to initialization of a shared resource (such as a Singleton), but it has a
problem: it’s not reliable. Furthermore, there’s virtually no portable way to
make it reliable in C++ (or in C) without substantively modifying the conventional
pattern implementation. To make matters even more interesting, DCLP
can fail for different reasons on uniprocessor and multiprocessor architectures.
This article explains why Singleton isn’t thread safe, how DCLP attempts to
address that problem, why DCLP may fail on both uni- and multiprocessor architectures,
and why you can’t (portably) do anything about it. Along the way,
it clarifies the relationships among statement ordering in source code, sequence
points, compiler and hardware optimizations, and the actual order of statement
execution. Finally, it concludes with some suggestions regarding how to add
thread-safety to Singleton (and similar constructs) such that the resulting code
is both reliable and efficient.
2 The Singleton Pattern and Multithreading
The traditional implementation of the Singleton Pattern [7] is based on making
a pointer point to a new object the first time the object is requested:
∗This is a slightly-modified version of an article that appeared in Dr. Dobbs Journal in
the July (Part I) and August (Part II), 2004, issues.
1
1 // from the header file
2 class Singleton {
3 public:
4 static Singleton* instance();
5 ...
6 private:
7 static Singleton* pInstance;
8 };
9
10 // from the implementation file
11 Singleton* Singleton::pInstance = 0;
12
13 Singleton* Singleton::instance() {
14 if (pInstance == 0) {
15
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值