Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# atomicity: assignment of int vs. long on x64 platform

I am looking at http://msdn.microsoft.com/en-us/library/aa691278(VS.71).aspx, which said read and write of int is atomic, while read and write of long may not be. Is that really true for 64 bit platform? Isn't it IntPtr.Size == 64 bit or long? Am I missing something or the language specs are not full enough?

More thoughts here as well: http://philosopherdeveloper.wordpress.com/2011/02/08/beware-assignment-atomic-assignment/

like image 864
Schultz9999 Avatar asked Sep 18 '12 23:09

Schultz9999


2 Answers

long is an atomic write on CPUs and platforms that have 64-bit words. e.g. if you run a 32-bit .NET application on a 64-bit computer, writes to long will not be atomic.

Mind you, atomicity is almost pointless if you can't make sure the compiler doesn't optimize access to that type of variable. e.g. you can't decorate a long field with volatile.

Operations on 64-bit fields are guaranteed to be atomic only in a 64-bit runtime environment

http://www.albahari.com/threading/part4.aspx

if you are running C# code on a 64 bit operating system in a 64 bit version of the CLR then reads and writes of 64 bit doubles and long integers are also guaranteed to be atomic

http://blogs.msdn.com/b/ericlippert/archive/2011/05/31/atomicity-volatility-and-immutability-are-different-part-two.aspx

like image 110
Peter Ritchie Avatar answered Sep 24 '22 08:09

Peter Ritchie


That's the documentation for VS2003 which corresponds to .NET Framework 1.1, which was only available in a 32-bit flavour (ignoring the very niche IA-64 editions for now).

The .NET Framework 2.0 introduced the x64 edition, where (as long as you're running in 64-bit mode) then certain (but not all) Int64 operations will be atomic.

Of course, if you want to be certain, use the Interlocked class.

like image 42
Dai Avatar answered Sep 20 '22 08:09

Dai