On this page
  1. atomic_compare_exchange_weak
  2. Include
  3. Signature & Overview
  4. Notes & Pitfalls
  5. Example

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

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