From lot of threads, like this one, I have found that C# int/float are thread safe. But I have seen lot of developers using Interlocked.Increment/CompareExchage for multi-threaded application. Any one can tell me the reason for using these constructs.
Update: I am aware about these constructs. I just wanted to ask If int is thread safe the why we need these constructs?
From lot of threads, like this one, I have found that C# int/float are
Share
it is not about thread safety of reading / writing. But about thread safety of the COMPLETE operation.
Increment is read, add 1, write. With interlocked that is guaranteed to happen in one “transaction.” Same with compare/exchange.
if you do not write it with some sort of locking, then you may get interrupted BETWEEN the operations.
Read
Inrecement
Write
Every of the 3 steps is atomic, but not the combination. Someone else may have changed the value when you write back – interlocked ensures the WHOLE operation is atomic.