Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

atomic_fetch_or — C23 atomic generic function

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

Version: C23

Syntax

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

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

Use it for concurrent reporting of independent flags: a bit set by one thread does not lose bits set by others. The example really combines initial 0x1 with mask 0x6, returns old value 1, and leaves all three bits set as 7.

The function does not support atomic pointers; object must be a compatible initialized atomic integer type. The non-_explicit form uses memory_order_seq_cst and need not be lock-free. OR can set bits but cannot clear them, and observing the old mask is not automatically an acknowledgement that another thread processed an event. 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 = 0x1u;
    unsigned previous = atomic_fetch_or(&flags, 0x6u);
    printf("%u %u\n", previous, atomic_load(&flags));
    return 0;
}

Result

1 7

Use it for concurrent reporting of independent flags: a bit set by one thread does not lose bits set by others. The example really combines initial `0x1` with mask `0x6`, returns old value `1`, and leaves all three bits set as `7`.

Sources