Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

atomic_thread_fence — C23 fence function

`atomic_thread_fence(order)` establishes a memory fence without reading or writing a particular atomic object. Relaxed has no effects; consume/acquire makes an acquire fence, release a release fence, acq_rel both, and seq_cst additionally participates in sequentially consistent ordering. It returns no value.

Version: C23

Syntax

void atomic_thread_fence(memory_order order);

atomic_thread_fence(order) establishes a memory fence without reading or writing a particular atomic object. Relaxed has no effects; consume/acquire makes an acquire fence, release a release fence, acq_rel both, and seq_cst additionally participates in sequentially consistent ordering. It returns no value.

A fence can connect ordinary data through a separate atomic marker. In the example the producer writes payload = 42, executes a release fence, and performs a relaxed store to ready; the consumer observes that store with a relaxed load, executes an acquire fence, and safely prints 42.

A fence alone transfers no value and synchronizes no threads: the C23-defined chain through an atomic modification and a load that reads that value (or the corresponding fence-operation variant) is required. If the load does not read the proper store, access to payload is not protected. A relaxed fence fixes nothing, while an unnecessarily strong seq_cst fence can cost more than the required acquire/release pair.

Examples

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

static int payload;
static atomic_int ready = 0;

static int writer(void *unused) {
    (void)unused;
    payload = 42;
    atomic_thread_fence(memory_order_release);
    atomic_store_explicit(&ready, 1, memory_order_relaxed);
    return 0;
}

static int reader(void *unused) {
    (void)unused;
    while (!atomic_load_explicit(&ready, memory_order_relaxed)) thrd_yield();
    atomic_thread_fence(memory_order_acquire);
    printf("%d\n", payload);
    return 0;
}

int main(void) {
    thrd_t producer, consumer;
    if (thrd_create(&consumer, reader, NULL) != thrd_success) return 1;
    if (thrd_create(&producer, writer, NULL) != thrd_success) return 1;
    thrd_join(producer, NULL);
    thrd_join(consumer, NULL);
    return 0;
}

Result

42

A fence can connect ordinary data through a separate atomic marker. In the example the producer writes `payload = 42`, executes a release fence, and performs a relaxed store to `ready`; the consumer observes that store with a relaxed load, executes an acquire fence, and safely prints `42`.

Sources