c# - .NET 中未对齐字段的读写绝对是原子的吗?

标签 c# .net atomic memory-alignment

C# 规范(ECMA-334ISO/IEC 23270)有一段关于读写的原子性:

12.5 Atomicity of variable references

Reads and writes of the following data types shall be atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types. In addition, reads and writes of enum types with an underlying type in the previous list shall also be atomic. Reads and writes of other types, including long, ulong, double, and decimal, as well as user-defined types, need not be atomic.

但我很难想象这总是正确的。例如,我可以使用 StructLayout attribute 布局结构。 ,并强制字段不对齐:

// sizeof(MyStruct) == 9
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct MyStruct
{
    public byte pad;   // Offset: 0
    public int value1; // Offset: 1
    public int value2; // Offset: 5
}

现在,当我这样做时,我认为写入 int不是原子的,因为它没有与自然边界对齐:

MyStruct myStruct = new MyStruct();
myStruct.value1 = 20;

那么,它是绝对原子的(如规范所述),还是不能保证是原子的(例如在 x86 上)?无论哪种方式,您有任何来源支持这一点吗?

最佳答案

我认为您是对的...在某些情况下,如果您故意不按自己的方式行事,系统将不会按照语言规范运行。重要的是,ECMA-335在分区 I 第 12.6.6 节中明确说明这一点:

A conforming CLI shall guarantee that read and write access to properly aligned memory locations no larger than the native word size (the size of type native int) is atomic (see §I.12.6.2) when all the write accesses to a location are the same size. Atomic writes shall alter no bits other than those written. Unless explicit layout control (see Partition II (Controlling Instance Layout)) is used to alter the default behavior, data elements no larger than the natural word size (the size of a native int) shall be properly aligned. Object references shall be treated as though they are stored in the native word size.

(粗体强调我的;斜体在规范中。)

关于c# - .NET 中未对齐字段的读写绝对是原子的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15249626/

相关文章:

c++ - C/C++ 中的结构赋值是原子的吗?

c - 以原子方式将值存储在 uint8_t (C)

javascript - 预览上传的图像

c# - ValueInjecter 空值

c# - 基于矢量的生成器是创建条形码的最佳方式吗?

.net - 正则表达式匹配除两个单词之外的任何内容

assembly - x86 上顺序一致的原子负载

c# - WPF 的新 DateTimePicker?

c# - 我可以在Unity 2018.4中使用MongoDB 3.6或更高版本吗?

.net - 无法在Win64位上创建64位的activex组件?