Atomic Operations


Atomic Operations

Atomic operations provide instructions that execute atomically—without interruption.

It is never possible for two atomic operations to occur on the same variable concurrently.

The kernel provides two sets of interfaces for atomic operations—

  1. Operates on integers
  2. Operates on individual bits.

The atomic operations are typically implemented as inline functions with inline assembly.

Atomic Integer Operations

The atomic integer methods operate on a special data type, atomic_t.

It also ensures that the data types are not passed to any non-atomic functions. The use of atomic_t ensures the compiler does not optimize access to the value

To define an integer atomic, you do

atomic_t v;

To convert an atomic_t to an int, you do

atomic_read()

printk("%d\n", atomic_read(&v));

A common use of the atomic integer operations is to implement counters. Protecting a sole counter with a complex locking scheme is overkill, so instead developers use atomic_inc() and atomic_dec(), which are much lighter in weight.

64 bit atomic operations

For portability, the size of atomic_t cannot change between architectures, so atomic_t is 32-bit even on 64-bit architectures. Instead, the atomic64_t type provides a 64-bit atomic integer that functions otherwise identical to its 32-bit counterpart

Usage is exactly the same, except that the usable range of the integer is 64, rather than 32, bits.

Atomic Bitwise Operations

Bitwise functions operate on generic memory addresses. The arguments are a pointer and a bit number.

results matching ""

    No results matching ""