I read this in the book C# 6.0 and the .NET 4.6 framework:
“assignments and simple arithmetic operations are not atomic”.
So, what d
Atomic operations are ones that cannot be interrupted partway through, such as by threading. Take for instance the statement
_value++;
If you have two threads executing this code at once with a starting value of 0
, you may have the following
_value
, 0_value
, 0_value
, 1_value
, 1so now, even though we've called an increment twice, the final value in _value
is 1
, not the expected 2
. This is because increment operators are not atomic.
The function Interlocked.Increment, however, is atomic, so replacing the above code with
Interlocked.Increment(ref _value);
Would solve the given race condition.
EDIT: As a point of etymology, "atomic" usually means "indivisible" - the chemistry term we're familiar with is a misnomer held over from the belief that atoms were indivisible, only for later discoveries to break them down further into subatomic, quark, and quanta levels.