atomic_compare_exchange_weak
Prev: atomic_fetch_add | Up: stdatomic.h | Next: threads.h
Rel: stdatomic.h, Synchronization & Coordination
Ref: cppreference — atomic_compare_exchange_weak
Tags: #public #prog #c #stdlib #stdatomic #tier/specialized
Include
#include <stdatomic.h>
Signature & Overview
bool atomic_compare_exchange_weak(volatile A *obj, T *expected, T desired);
Atomically replaces *obj with desired if *obj == *expected (else loads current *obj into *expected).
Notes & Pitfalls
- Always use
_weakinside awhileloop (may spuriously fail on LL/SC CPUs like ARM, but generates faster code); use_strongfor a single non-loop check. - Updates
expectedon failure so the next loop iteration retries cleanly.
Example
#include <assert.h>
#include <stdatomic.h>
int main(void) {
atomic_int val = 10;
int expected = 10;
while (!atomic_compare_exchange_weak(&val, &expected, expected * 2)) {}
assert(atomic_load(&val) == 20);
}
Linked from
Related notes
- tuts/c/stdlib/stdatomic/atomic_fetch_add 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/c/stdlib/threads Linked here; shared tags: #c, #prog, #stdlib
- tuts/programming/concurrency/synchronization_and_coordination Linked here; shared tags: #prog
- tuts/c/stdlib/stdatomic/atomic_load shared tags: #c, #prog, #stdatomic, #stdlib, #tier
- 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