c# – Atomicity of the operation of obtaining an instance of a class on an x64 application

Question:

Assignment atomicity can be achieved with System.Threading.Interlocked

Interlocked.Exchange(ref toItem, fromItem);

But how to get an instance of a class atomically, because System.Threading.Interlocked does not have a Read(ref object) method, there is only Read(ref long) ?

TObject obj = somethingObject; 
//Сомнение атомарности. 
//Поскольку передача указателя x64 не умещается в такт процессора, 
//и не гарантирует атомарности.

please do not give examples with lock , because I'm not interested in them.

Answer:

The operation of reading an object reference is always atomic. This is a consequence of a basic .NET principle: if your code does not contain unsafe calls, there is no way you can get an invalid reference to an object.

As a consequence, reading int, pointers, and IntPtr are always atomic. Moreover, reading a long is also atomic on a 64-bit system (the Interlocked.Read(ref long) method you found is for x86 or AnyCPU platforms)

However, one must understand that Interlocked operations are not only atomic, they are also memory barriers. Therefore, you cannot read a shared variable as TObject obj = somethingObject – this reading can give stale data.

To read, you need to use the Volatile.Read method:

TObject obj = Volatile.Read(ref somethingObject);
Scroll to Top