[ Previous | Next | Contents | Glossary | Home | Search ]
AIX Version 4.3 Base Operating System and Extensions Technical Reference, Volume 1

fetch_and_add Subroutine

Purpose

Updates a single word variable atomically.

Library

Standard C library (libc.a)

Syntax

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

Description

The fetch_and_add subroutine increments 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 subroutine requires very little overhead, and provided that the counter variable fits in a single machine word, this subroutine provides a highly efficient way of performing this operation.

Note: The word containing the counter variable must be aligned on a full word boundary.

Parameters

word_addr Specifies the address of the word variable to be incremented.
value Specifies the value to be added to the word variable.

Return Values

This subroutine returns the original value of the word.

Implementation Specifics

This subroutine is part of the Base Operating System (BOS) Runtime.

Related Information

The fetch_and_and subroutine, fetch_and_or subroutine, compare_and_swap subroutine.


[ Previous | Next | Contents | Glossary | Home | Search ]