I have this struct:
[StructLayout(LayoutKind.Sequential)]
public readonly unsafe struct MyStruct
{
public readonly byte* Pointer;
public readonly object Owner;
}
Most operations depend on Pointer
field. I need to replace this struct, which is stored as a field of a class, with another one concurrently while it is being used by multiple threads. The new one still has a valid pointer and all methods that use the struct first cache the pointer as a local variable if they touch the pointer multiple times. The Owner
field is only needed to dispose some native resources.
Replacing the entire struct is not atomic, but old and new pointers could be replaced seamlessly for the calling methods. Therefore I'm safe if every field of a struct is replaced atomically. I use locks in the replace method and other methods that use both fields.
The question is: does CLR guarantee that the pointer fields are replaced atomically even if the entire structure could be torn?
It should be so, because even if the struct were replaced by memcpy, it is aligned as a field of a class and a minimal atomic copy chunk is a native int. Also likely the struct is not copied by memcpy, but CLR copies it field-by-field. But if this is not the case I'm risking to introduce a subtle bug that will happen once per many millions calls with a segfault, with pointer value being partially updated.