Single-core, multi-core CPU atomic operation
I. What is an "atomic operation":
Atomic operations are: one or a series of operations that cannot be interrupted, that is, operations that are not interrupted by the thread scheduling mechanism, without any context switches during the run.
Two. Why focus on atomic operations?
1. If it is determined that an operation is atomic, it is not necessary to protect the operation by adding a lock that consumes expensive performance overhead. -(clever use of atomic manipulation and implementation of lock-free programming)
2. A mutex (mutex) can be implemented with atomic manipulation. (mutex_lock_t in Linux)
3. With a mutex, you can make more operations into atomic operations.
Three. Atomic operation of a single-core CPU:
In a single-core CPU, actions that can be done in one instruction can be seen as atomic operations, because interrupts occur only between instructions.
Four. Atomic operation of multi-core CPUs:
In the age of Multicore CPUs (indeed Moore's law is somewhat outdated, we need more CPUs, not faster CPUs, inability to handle heat dissipation problems in fast CPUs), multiple independent CPUs running in the system, and even operations that can be done in a single instruction can be disrupted. A typical example is the decl instruction (decrement instruction), which is subdivided into three processes: read----and-write, which involves two memory operations. If multiple CPUs are running several processes simultaneously executing this instruction on the same block of memory, the situation is unpredictable.
Five. How to achieve the atomicity of ++i and i++:
1. Single CPU, use the lock or prohibit multi-threaded scheduling, because its own single-core CPU concurrency is pseudo-concurrency. (In a single-core CPU, it is not necessary to use multithreading in a program that is not blocked).
2. multicore CPUs need to lock the bus with the help of the CPU-provided lock. Prevents other CPUs from accessing memory during "read, modify, write" throughout the process. (then "read-write, modify, write" This operation will not occur in a single core thread switch it?) )
Single-core, multi-core CPU atomic operation