fetch_and_add and fetch_and_addlp Subroutines

Purpose

Updates a variable atomically.

Library

Standard C library (libc.a)

Syntax

#include <sys/atomic_op.h>
int fetch_and_add ( addr,  value)
atomic_p addr;
int value;

long fetch_and_addlp ( addr,  value)
atomic_l addr;
ulong value;

Description

The fetch_and_add and fetch_and_addlp subroutines increment one word in a single atomic operation. This operation is useful when a counter variable is shared between several threads or processes. When updating such a counter variable, it is important to make sure that the fetch, update, and store operations occur atomically (are not interruptible). For example, consider the sequence of events which could occur if the operations were interruptible:

  1. A process fetches the counter value and adds one to it.
  2. A second process fetches the counter value, adds one, and stores it.
  3. The first process stores its value.

The result of this is that the update made by the second process is lost.

Traditionally, atomic access to a shared variable would be controlled by a mechanism such as semaphores. Compared to such mechanisms, the fetch_and_add and fetch_and_addlp subroutines require very little increase in processor usage.

For 32-bit applications, the fetch_and_add and fetch_and_addlp subroutines are identical and operate on a word aligned single word (32-bit variable aligned on a 4-byte boundary).

For 64-bit applications, the fetch_and_add subroutine operates on a word aligned single word (32-bit variable aligned on a 4-byte boundary) and the fetch_and_addlp subroutine operates on a double word aligned double word (64-bit variable aligned on an 8-byte boundary).

Parameters

Item Description
addr Specifies the address of the variable to be incremented.
value Specifies the value to be added to the variable.

Return Values

This subroutine returns the original value of the variable.