atomic operations and atomic transactions

user2204378 picture user2204378 · Mar 27, 2013 · Viewed 11.4k times · Source

Can someone explain to me, whats the difference between atomic operations and atomic transactions? Its seems to me that these two are the same thing.Is that correct?

Answer

Charley Moore picture Charley Moore · Jan 19, 2015

The concept of Atomicity is common between atomic transactions and atomic operations, but they are usually related to different domains.

Atomic Transactions are associated with Database operations where a set of actions must ALL complete or else NONE of them complete. For example, if someone is booking a flight, you want to both get payment AND reserve the seat OR do neither. If either one were allowed to succeed without the other also succeeding, the database would be inconsistent.

Atomic Operations on the other hand are usually associated with low-level programming with regards to multi-processing or multi-threading applications and are similar to Critical Sections. For example, if two threads both access and modify the same variable, each thread goes through the following steps:

  1. Read the variable from storage into local memory.
  2. Modify the value in local memory.
  3. Write the modified value back to the original storage location.

But in a multi-threaded system an interrupt or other context switch might happen after the first process has read the value but has not written it back. The second process (or interrupt) will then read and modify the OLD value and write its modified value back to storage. When the first process is re-enabled, it doesn't know that something might have changed so it writes back its change to the original value. Hence the operation that the second process did to the variable will be lost. If an operation is atomic, it is guaranteed to complete without being interrupted once it begins. This is usually accomplished using hardware-level primitives like Test-and-Set or Compare-and-Swap.