In C#, what does “atomic” mean?

后端 未结 2 665
一向
一向 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 12:57

    An atom is indivisible. Atomic operations are "indivisible" operations, which cannot be divided, e.g., interrupted.

    Microprocessors do not execute sequentially, that is, instruction after instruction, just like written in a program. There are external objects, which can change execution flow. A good example are interrupts.

    So, you may know the MOV instruction, which is available on pretty much all processors.
    Imagine that it is executed by the CPU. a 32-bit value is moved into a 32-bit register.
    Now, after 16 bits have been moved, an interrupt request occurs.

    • An atomic MOV instruction will not stop but will execute to the end and then the CPU will handle the interrupt
    • A MOV instruction that is not atomic will immediately be stopped and the interrupt is executed. The problem is, if the interrupt accessed the register, which was written to by the MOV, the content is unclear because the MOV operation is only half-finished!

    Now, on usual processors, MOVs operating on the processor's word size are atomic. If a processor word is 16 bits wide, a 16-bit MOV instruction will be atomic.
    However, a 32-bit MOV operation would not be atomic. Such a non-atomic MOV instruction is normally not provided by the instruction set but by some higher-level language as with C's long long or C#'s long. Operations on these data types are not guaranteed to be atomic!

提交回复
热议问题