Introduction to atomic operations
Atomic operations are indivisible (hence the word atomic, from the Greek ἄτομος, atomos, indivisible).
In this section, we will introduce atomic operations, what they are, and some reasons to use (and not to use!) them.
Atomic operations versus non-atomic operations – an example
If you remember the simple counter example from Chapter 4, we needed to use a synchronization mechanism (we used a mutex) for modifying the counter variable from different threads to avoid race conditions. The cause of the race condition was that incrementing the counter required three operations: reading the counter value, incrementing it, and writing the modified counter value back to memory. If only we could do that in one go, there would be no race condition.
This is exactly what could be achieved with an atomic operation: if we had some kind of atomic_increment
operation, each thread would read, increment, and write...