In C#, what does “atomic” mean?

后端 未结 2 664
一向
一向 2021-02-06 12:19

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

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-06 13:06

    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

    • Thread A reads _value, 0
    • Thread A adds 1, 1
    • Thread B reads _value, 0
    • Thread B adds 1, 1
    • Thread A assigns to _value, 1
    • Thread B assigns to _value, 1

    so 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.

提交回复
热议问题