《程序员的自我修养》的笔记-第29页

ziyoudefeng
ziyoudefeng (娜娜,有你生活真幸福~~)

读过 程序员的自我修养

  • 章节名:过度优化中CPU的动态调度问题
  • 页码:第29页 2012-12-22 14:21:19
25人阅读

2013-04-15 22:00:19 ziyoudefeng

A* a = new A("plop");

// Looks simple enough.
// But this can be split into three parts.
(a) allocate Memory
(b) Call constructor
(c) Assign value to 'a'

// No problem here:
// The compiler is allowed to do this:
(a) allocate Memory
(c) Assign value to 'a'
(b) Call constructor.
// This is because the whole thing is between two sequence points.

// So what is the big deal.
// Simple Double checked lock. (I know there are many other problems with this).
if (a == null) // (Point B)
{
Lock lock(mutex);
if (a == null)
{
a = new A("Plop"); // (Point A).
}
}
a->doStuff();

// Think of this situation.
// Thread 1: Reaches point A. Executes (a)(c)
// Thread 1: Is about to do (b) and gets unscheduled.
// Thread 2: Reaches point B. It can now skip the if block
// Remember (c) has been done thus 'a' is not NULL.
// But the memory has not been initialized.
// Thread 2 now executes doStuff() on an uninitialized variable.

// The solution to this problem is to move the assignment of 'a'
// To the other side of the sequence point.
if (a == null) // (Point B)
{
Lock lock(mutex);
if (a == null)
{
A* tmp = new A("Plop"); // (Point A).
a = tmp;
}
}
a->doStuff();

// Of course there are still other problems because of C++ support for
// threads. But hopefully these are addresses in the next standard.


> ziyoudefeng的所有笔记(109篇)

ziyoudefeng对本书的所有笔记  · · · · · ·

  • 第320页

    再执行crt1.o之前,链接器,装载器这些东西做的工作真不少。 编译器,链接器自然不用说了,生成...

  • 第319页

    本篇笔记全文摘自后面参考文献列出的地址,不过原文中有一些错别字,我这里把错别字改了改,然后...

  • 第29页
  • 第93页

    在GCC中,我们可以通过使用“__attribute__((weakref))”这个扩展关键字来声明对一个外..

说明  · · · · · ·

表示其中内容是对原文的摘抄