atomic_fetch_add, atomic_fetch_add_explicit

From cppreference.com
< clrm; | atomic
Defined in header <stdatomic.h>
C atomic_fetch_add( volatile A* obj, M arg );
(1) (since C11)
C atomic_fetch_add_explicit( volatile A* obj, M arg, memory_order order );
(2) (since C11)

Atomically replaces the value pointed by obj with the result of addition of arg to the old value of obj, and returns the value obj held previously. The operation is read-modify-write operation. The first version orders memory accesses according to memory_order_seq_cst, the second version orders memory accesses according to order.

This is a generic function defined for all atomic object types A. The argument is pointer to a volatile atomic type to accept addresses of both non-volatile and volatile (e.g. memory-mapped I/O) atomic variables.M is either the non-atomic type corresponding to A if A is atomic integer type, or ptrdiff_t if A is atomic pointer type.

For signed integer types, arithmetic is defined to use twos complement representation. There are no undefined results. For pointer types, the result may be an undefined address, but the operations otherwise have no undefined behavior.

Parameters

obj - pointer to the atomic object to modify
arg - the value to add to the value stored in the atomic object
order - the memory synchronization ordering for this operation: all values are permitted

Return value

The value held previously be the atomic object pointed to by obj.

Example

#include <stdio.h>
#include <threads.h>
#include <stdatomic.h>

atomic_int acnt;
int cnt;

int f(void* thr_data)
{
    for(int n = 0; n < 1000; ++n) {
        atomic_fetch_add_explicit(&acnt, 1, memory_order_relaxed); // atomic
        ++cnt; // undefined behavior, in practice some updates missed
    }
    return 0;
}

int main(void)
{
    thrd_t thr[10];
    for(int n = 0; n < 10; ++n)
        thrd_create(&thr[n], f, NULL);
    for(int n = 0; n < 10; ++n)
        thrd_join(thr[n], NULL);

    printf("The atomic counter is%u\n", acnt);
    printf("The non-atomic counter is%u\n", cnt);
}

Possible output:

The atomic counter is 10000
The non-atomic counter is 9511

References

  • C11 standard (ISO/IEC 9899:2011):
  • 7.17.7.5 The atomic_fetch and modify generic functions (p: 284-285)

See also

atomic subtraction
(function)