On this page
atomic_fetch_add
Prev: atomic_load | Up: stdatomic.h | Next: atomic_compare_exchange_weak
Rel: stdatomic.h, Synchronization & Coordination
Ref: cppreference — atomic_fetch_add
Tags: #public #prog #c #stdlib #stdatomic #tier/specialized
Include
#include <stdatomic.h>
Signature & Overview
T atomic_fetch_add(volatile A *obj, M arg);
Atomically adds arg to *obj and returns the previous value without a mutex.
Notes & Pitfalls
- Returns the previous value before adding: Great for lock-free ID generators and reference counters.
Example
#include <assert.h>
#include <stdatomic.h>
int main(void) {
atomic_int next_id = 1;
int prev = atomic_fetch_add(&next_id, 1);
assert(prev == 1 && atomic_load(&next_id) == 2);
}
Linked from
Related notes
- tuts/c/stdlib/stdatomic/atomic_compare_exchange_weak Linked here; links to this page; shared tags: #c, #prog, #stdatomic, #stdlib, #tier
- tuts/c/stdlib/stdatomic/atomic_load Linked here; links to this page; shared tags: #c, #prog, #stdatomic, #stdlib, #tier
- tuts/c/stdlib/stdatomic Linked here; links to this page; shared tags: #c, #prog, #stdatomic, #stdlib
- tuts/programming/concurrency/synchronization_and_coordination Linked here; shared tags: #prog
- tuts/c/stdlib/assert/assert shared tags: #c, #prog, #stdlib, #tier
- tuts/c/stdlib/assert/static_assert shared tags: #c, #prog, #stdlib, #tier
- tuts/c/stdlib/ctype/isalpha shared tags: #c, #prog, #stdlib, #tier
- tuts/c/stdlib/ctype/isdigit shared tags: #c, #prog, #stdlib, #tier
- tuts/c/stdlib/ctype/isspace shared tags: #c, #prog, #stdlib, #tier
- tuts/c/stdlib/ctype/tolower shared tags: #c, #prog, #stdlib, #tier