Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

atomic_compare_exchange_weak — C23 atomic generic function

`atomic_compare_exchange_weak(object, expected, desired)` has the same success store and failure update of `*expected` as the `strong` form, but it may return `false` spuriously even when the values compare equal. The read-modify-write on `object` remains atomic; the failure write to `expected` is an ordinary non-atomic write.

Version: C23

Syntax

bool atomic_compare_exchange_weak(volatile A *object, C *expected, C desired);

atomic_compare_exchange_weak(object, expected, desired) has the same success store and failure update of *expected as the strong form, but it may return false spuriously even when the values compare equal. The read-modify-write on object remains atomic; the failure write to expected is an ordinary non-atomic write.

It is intended mainly for retry loops where an occasional spurious failure does not change the algorithm and may permit a cheaper hardware instruction. The example starts with incorrect expected = 3; the first failure writes 7 there, and the loop eventually changes the atomic value to 9.

Code must retry through interference from other threads and recompute desired when it depends on the updated expected. The non-_explicit form uses memory_order_seq_cst; invalid pointers, a race on non-atomic expected, or assuming one attempt is enough violates the contract. ABA remains possible. Violating the pointer requirements—including an invalid pointer, an incompatible pointed-to type, or a nonmodifiable expected object—has undefined behavior; an unsynchronized race on expected likewise has undefined behavior.

C23 compares the contents, that is, the value representations designated by object and expected, rather than only their mathematical equality; the atomic read-modify-write applies to object, while expected is ordinary non-atomic storage. Concurrent unsynchronized access to expected creates a data race and undefined behavior. This generic function name may be a macro or an external identifier; suppressing the macro to call an actual function, or defining an external identifier with that name, has undefined behavior.

Examples

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

int main(void) {
    atomic_int value = 7;
    int expected = 3;
    int failures = 0;

    while (!atomic_compare_exchange_weak(&value, &expected, 9)) {
        ++failures;
    }
    printf("%d %d %d\n", atomic_load(&value), expected, failures >= 1);
    return 0;
}

Result

9 7 1

It is intended mainly for retry loops where an occasional spurious failure does not change the algorithm and may permit a cheaper hardware instruction. The example starts with incorrect `expected = 3`; the first failure writes `7` there, and the loop eventually changes the atomic value to `9`.

Sources