[ Next Article | Previous Article | Book Contents | Library Home | Legal | Search ]
Base Operating System and Extensions Technical Reference, Volume 1

fetch_and_and or fetch_and_or Subroutine

Purpose

Sets or clears bits in a single word variable atomically.

Library

Standard C library (libc.a)

Syntax

#include <sys/atomic_op.h>
uint fetch_and_and (word_addr, mask)
atomic_p word_addr;
int mask;
uint fetch_and_or (word_addr, mask)
atomic_p word_addr;
int mask;

Description

The fetch_and_and and fetch_and_or subroutines respectively clear and set bits in one word, according to a bit mask, in a single atomic operation. The fetch_and_and subroutine clears bits in the word which correspond to clear bits in the bit mask, and the fetch_and_or subroutine sets bits in the word which correspond to set bits in the bit mask.

These operations are useful when a variable containing bit flags is shared between several threads or processes. When updating such a variable, it is important that the fetch, bit clear or set, 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 flags variable and sets a bit in it.
  2. A second process fetches the flags variable, sets a different bit, and stores it.
  3. The first process stores its value.

The result 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_and and fetch_and_or subroutines require very little overhead, and provided that the flags variable fits in a single machine word, they provide a highly efficient way of performing this operation.

Note: The word containing the flag bits must be aligned on a full word boundary.

Parameters

word_addr Specifies the address of the single word variable whose bits are to be cleared or set.
mask Specifies the bit mask which is to be applied to the single word variable.

Return Values

These subroutines return the original value of the word.

Implementation Specifics

These subroutines are part of the Base Operating System (BOS) Runtime.

Related Information

The fetch_and_add subroutine, compare_and_swap subroutine.


[ Next Article | Previous Article | Book Contents | Library Home | Legal | Search ]