The C# specification (ECMA-334 and ISO/IEC 23270) has a paragraph about the atomicity of reads and writes:
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.
But I have a hard time imagining that to be always true. For example, I can layout a struct using the StructLayout
attribute, and force the fields to be unaligned:
// 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
}
Now when I do this, I would think the write to the int
is not atomic, since it is not aligned to the natural boundary:
MyStruct myStruct = new MyStruct();
myStruct.value1 = 20;
So, is it definitely atomic (like the specification says), or is it not guaranteed to be atomic (e.g. on x86)? Either way, do you have any sources to back this up?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…