I think I read that the operations on Int32 and Int64 are truly atomic on 64-bit systems (ie. the assembly/application is compiled as 64-bit) in .Net.
Is that true?
I can not find the MSDN citation, so I thought I’d ask you guys here.
I’m wondering if to use the Interlocked class to check and decrement the value of an Int32 from multiple threads or not, and I’m compiling it as a 64-bit application.
There’s a little help in a documentation of these methods on MSDN, but I’m not sure if I understood it correctly.
Thanks
Re incrementing a value:
A manual increment is never guaranteed to be atomic – not on x86, not on x64; it is four operations: load, load, add, store. The JIT might spot a load-constant-1 (
ldc_i4_1/ldc_i8) and make it a bit simpler, but fundamentally: that is not a single atomic operation. You cannot do a thread-safe increment (that does not risk lost updates) in multi-threaded code without using some kind of locking construct, or usingInterlocked.Re assignment atomicity (aka torn values):
Operations on
int(etc) are guaranteed to be atomic by the language specification; operations onlong(etc) are not guaranteed to be. Yes, it likely that they are atomic on x64, but here’s the rub: when worrying about atomicity, you must be dealing with threading. When dealing with threading, you don’t look at the implementation, i.e. what happens to be – because that is not guaranteed, and you presumably care that this code does what it intends. As such IMO you must only concern yourself with what is guaranteed, and that means: you can’t rely onlong(etc) being atomic.Instead, use
Interlocked.Increment,Interlocked.Add, etc.