Search code examples
c#.net-corevolatileunsafe

volatile Read/Write in C#(DotNet Core) for pointers


Platform: DotNet Core 2 on Linux

Is C# pointer dereference volatile or how to make it volatile?

Our team is working on some crazy stuff require ultra-low latency but still need to be written in C#. We need to get value from a shared memory as low latency as possible and we will busy waiting on this. So pointer reference to shared memory is the fastest way I could image. But really concern about JIT will try to cache the value.

I think Volatile.Read(IntPtr) might do the job but seems IntPtr is an immutable object so the application will create lots of garbage if we keep allocating new ones.

Thanks @Eric pointed out that this is not creating garbage. But my question still there. Does Volatile.Read(IntPtr) will do the job or not? As the IntPtr is not volatile, but the value it pointing to is.

Also any chance I can use compare and swap function on the pointer?

 unsafe
        {
             var access = MemoryMappedFile.CreateFromFile("Test.mem");
            IntPtr ptr = access.SafeMemoryMappedFileHandle.DangerousGetHandle();
             int* p = (int*)ptr.ToPointer();
             p++; //How to get value of this p, if the memory will be updated by another process.

        }

Solution

  • Volatile.Read(ref *p);
    

    An example

    But you must guarantee that the address is 4-bytes aligned. Otherwise reading will not be atomic.