代码之家  ›  专栏  ›  技术社区  ›  Eloff

理解clr2.0内存模型

  •  13
  • Eloff  · 技术社区  · 16 年前

    6 rules that describe the CLR 2.0+ memory model (这是实际的实现,而不是任何ECMA标准)我写下了我试图弄明白这一点的尝试,主要是作为一种逃避的方式,但如果我在逻辑上犯了错误,至少这里有人能够在它引起我悲伤之前抓住它。

    • 规则1:负载之间的数据依赖性
    • 规则2:所有商店都有发布语义, i、 e.货物或仓库在运输后不得移动 一个。
    • 先走一步。
    • 商店可能会跨越一个完整的障碍 获取,联锁,交换, 联锁、比较交换等)。
    • 规则5:加载并存储到堆 可能永远不会被介绍。
    • 规则6: 当连接相邻荷载和 同一地点的商店。

    我在努力理解这些规则。

    x = y
    y = 0 // Cannot move before the previous line according to Rule 1.
    
    x = y
    z = 0
    // equates to this sequence of loads and stores before possible re-ordering
    load y
    store x
    load 0
    store z
    

    这样看来,可以在加载y之前将加载0上移到,但存储可能根本不会重新排序。因此,如果线程看到z==0,那么它也会看到x==y。

    满满的屏障就像沙子里的一条线,装载和储存的东西无法移动。

    我猜第六条规则意味着如果你这么做了:

    x = y
    x = z
    

    然后CLR可以同时删除对y的加载和对x的第一个存储。

    x = y
    z = y
    // equates to this sequence of loads and stores before possible re-ordering
    load y
    store x
    load y
    store z
    // could be re-ordered like this
    load y
    load y
    store x
    store z
    // rule 6 applied means this is possible?
    load y
    store x // but don't pop y from stack (or first duplicate item on top of stack)
    store z
    

    如果y是不稳定的呢?我在规则中没有看到任何禁止执行上述优化的内容。这并不违反双重检查锁定,因为两个相同条件之间的lock()会阻止负载移动到相邻位置,根据规则6,这是唯一可以消除负载的时间。

    所以我想除了第五条我都懂了。有人想开导我(或者纠正我,或者在上面加点什么?)

    1 回复  |  直到 16 年前
        1
  •  11
  •   Bradley Grainger    16 年前

    Joe Duffy在第517-18页讨论了规则5 Concurrent Programming on Windows :

    例如,负载可能

    MyObject mo = ...;
    int f = mo.field;
    if (f == 0)
    {
        // do something
        Console.WriteLine(f);
    }
    

    将mo.field读入变量f和 f的后继用法 写线够长了,一个 编译器可能会决定 ... 如果 同时写入mo.field。这个 if块可能包含假定 读取到f中的值保持为0,并且 reads的引入可能会打破 禁止挥发性物质使用 禁止普通变量使用它 也指GC堆内存。

    blogged about one important place where this matters :引发事件的标准模式。

    EventHandler handler = MyEvent;
    if (handler != null)
        handler(this, EventArgs.Empty);
    

    为了防止在单独线程上删除事件处理程序时出现问题,我们读取 MyEvent 并且仅在委托为非null时调用事件处理程序。

    MyEvent公司 再次,而不是使用本地,这将引入竞争条件。