Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

atomic_fetch_and — C23 atomic generic function

`atomic_fetch_and(object, operand)` from `<stdatomic.h>` atomically performs `*object &= operand` on an atomic integer type and returns the value from before the operation. It is one read-modify-write operation.

Version: C23

Syntax

C atomic_fetch_and(volatile A *object, M operand);

atomic_fetch_and(object, operand) from <stdatomic.h> atomically performs *object &= operand on an atomic integer type and returns the value from before the operation. It is one read-modify-write operation.

Use it to clear selected bits concurrently without overwriting flags set in the meantime by other threads. The example starts with mask 0x7, atomically clears bit 0x2 through ~0x2u, returns old value 7, and leaves 5.

The function does not accept atomic pointers, and object must point to a compatible initialized atomic integer type. The non-_explicit form uses memory_order_seq_cst and need not be lock-free. The mask must have the intended width and signedness; one mask operation does not create an invariant spanning other atomic objects. The supported atomic integer types explicitly exclude _Atomic bool; this operation has no pointer form.

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 <stdio.h>

int main(void) {
    atomic_uint flags = 0x7u;
    unsigned previous = atomic_fetch_and(&flags, ~0x2u);
    printf("%u %u\n", previous, atomic_load(&flags));
    return 0;
}

Result

7 5

Use it to clear selected bits concurrently without overwriting flags set in the meantime by other threads. The example starts with mask `0x7`, atomically clears bit `0x2` through `~0x2u`, returns old value `7`, and leaves `5`.

Sources