1

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.

V.B.
  • 6,236
  • 1
  • 33
  • 56
  • Try it and see. –  Apr 26 '19 at 01:16
  • I bet it will work, the question is mostly about if this is guaranteed and a part of specs. – V.B. Apr 26 '19 at 01:18
  • Ah, no problem. –  Apr 26 '19 at 01:24
  • Based on duplicate you are safe for 32bit case... does not sound like 64bit has defined behavior. – Alexei Levenkov Apr 26 '19 at 01:42
  • @AlexeiLevenkov both fields are native word size. The entire struct is not atomic, it's clear without the "duplicate" answer, since the entire struct is two words both on 32 and 64. But when it copied - is it copied field-by-field or in some weirdly optimized way that could break atomicity of fields? – V.B. Apr 26 '19 at 01:46
  • I don't see how they can do "weirdly optimized way" and at the same time guarantee that both read and write to those fields are atomic. If you feel that there is some reason why it can be done differently - edit and I'll reopen... Something like "does C#/CLI spec requires struct copying to match field-by-field behavior (in particular for atomicity)" - also you may want to read such portion of the spec first... – Alexei Levenkov Apr 26 '19 at 01:53
  • I have just scanned ECMA 335 for every mention of the word "copy", 334 is on the way. – V.B. Apr 26 '19 at 01:55
  • @AlexeiLevenkov I was thinking from writer perspective, but from what you wrote it's clear that readers do not know that the struct is being copied, so if they have the guarantee that every field is atomic then any write optimization cannot break that contract. Makes sense. – V.B. Apr 26 '19 at 02:02

0 Answers0