gpt4 book ai didi

c# - 引用类型的字段如何可以是非 volatile 的?

转载 作者:太空宇宙 更新时间:2023-11-03 18:31:11 25 4
gpt4 key购买 nike

这是MSDN关于volatile:

The volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times.

The volatile keyword can be applied to fields of these types: Reference types.

这个状态意味着默认情况下引用类型的字段不是可变的。
我认为将引用类型字段视为包含对象地址的值类型字段是可以的。然后就变成了类似于int类型。乔·阿尔巴哈里 gives some examples .

但是!... 与通常的值类型不同,GC 会在压缩堆并相应地更改引用时将对象移动到内存中。因此,“最新值”必须始终存在。如果是这样,波动性的概念如何应用于引用类型?

最佳答案

This state implies that fields of reference type are not volatile by default.

当然。默认情况下,没有字段被视为 volatile,因为 volatile 可能会带来相当大的性能成本。

I think it's ok to treat reference-type field as a field of value type containing the address of the object. Then it becomes similar to int type.

假设这可以毫无问题地完成。所以呢?默认情况下,intbool 等标量类型的字段也不会被视为 volatile。

Unlike usual value types GC moves objects into memory when it compacts the heap and changes the references accordingly. Hence 'the most up-to-date value' must always be there. And if so how does the concept of volatility apply to reference types?

您对 volatile 的实用性有点困惑。它要解决的问题不仅是 (A) 最新的值不存在(尽管 volatile 语义确实保证对值的任何写入都会可以通过抽象时间线中跟随它们的任何读取观察到 ¹)。

除此之外,它还旨在解决情况 (B),即编译器假设它生成的代码是唯一修改该值的一方(或者该值未被修改all),这意味着它不会选择从字段中读取值,而是使用手头已有的“缓存副本”。如果值 同时被第三方修改,这显然会导致程序使用错误的数据进行计算。

有关更多信息,您可以引用这个优秀的analysis作者 Igor Ostrovsky,其中 (A) 称为“处理器优化”,(B) 称为“编译器优化”。


¹ 请注意,这不是一个严格的定义,而只是一个粗略的近似值。

关于c# - 引用类型的字段如何可以是非 volatile 的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22219071/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com