First, the concept
Atomic operations provide instructions for atomic execution, with no interruption in the middle. Just as atoms are thought to be indivisible particles, atomic manipulation (atomic operation) is an inseparable operation.
The self-adding 1 operation of a variable in C language seems simple, as if only one instruction is needed without interruption. But this operation is implemented, the CPU execution is a process, divided into read to register, Register mathematical operation, write back to memory. This actual situation, will give us the process of writing a hidden danger, for example, Ming.
Thread 1 Thread 2
---------------------------------------------
Get I (7) Get I (7)
Increment I (7->8)
---increment i (7->8)
Write back I (8)----
---write back I (8)
It can be seen that the process of the non-pass to the same variable, since the addition of 1 operation two times, but the result is only added 1 once, this result is not what we wanted beforehand. If there is a way to read, calculate, write back the entire process of the variable, and not be interrupted by another process, the situation would be much better:
Thread 1 Thread 2
--------------------------------------------------------
Get, increment, and store I (7->8)---
---get, increment, and store I (8->9)
Or:
Thread 1 Thread 2
--------------------------------------------------------
---get, increment, and store I (7->8)
Get, increment, and store I (8->9)---
This operation is atomic and takes advantage of an exclusive memory implementation strategy, which of course requires the CPU's instruction set to provide such a lock memory unit operation.
Ii. Methods of Use
1. Define an atomic variable and initialize
atomic_t v = atomic_init (0);
2, atomic variable self-minus 1
Atomic_dec (&V);
3. Atom variable Self-add 1
Atomic_inc (&V);
4. Read the value of the atomic variable
Atomic_read (&V);
5, atomic variable self minus 1, and compared with 0, if 0 returns true, otherwise false
Atomic_dec_and_test (&V);
Reference: Linux Zhongyuan Sub-operation implementation mode
Linux System Atomic Operations