C# 规范(ECMA-334 和 ISO/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/