CKTIS / C++
std::atomic_thread_fence — synchronization using memory fences
std::atomic_thread_fence establishes memory-ordering constraints without reading or writing a specified object. Inter-thread synchronization requires appropriately connected atomic operations; fences alone are not enough.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
#include <atomic>
std::atomic_thread_fence(order); // order: std::memory_order; returns voidstd::atomic_thread_fence(order) from <atomic> returns void and does not throw exceptions. A fence does not operate on a particular atomic object. It is neither a lock nor an unconditional command to “flush the cache”.
In C++23, std::memory_order_relaxed has no effect. Both std::memory_order_consume and std::memory_order_acquire create an acquire fence. std::memory_order_release creates a release fence, and std::memory_order_acq_rel creates a fence with both acquire and release semantics. std::memory_order_seq_cst creates a sequentially consistent acquire and release fence.
In the example, the write to payload precedes the release fence, followed by the atomic store to ready. The load of ready that observes true from that store precedes the acquire fence. This chain synchronizes the fences and makes the write to payload happen before its read: the result is 42, without a data race. Merely adding fences without this atomic connection does not protect ordinary data.
A release fence can also connect to an acquire load, or a release store to an acquire fence, with the required reads-from connection. std::atomic_signal_fence constrains ordering only between a thread and a signal handler executed in that same thread. The supplied source is an evolving standard draft, not frozen C++23 text.
Examples
#include <atomic>
#include <iostream>
#include <thread>
int main() {
int payload = 0;
std::atomic<bool> ready{false};
std::thread producer([&] {
payload = 42;
std::atomic_thread_fence(std::memory_order_release);
ready.store(true, std::memory_order_relaxed);
});
while (!ready.load(std::memory_order_relaxed)) {
std::this_thread::yield();
}
std::atomic_thread_fence(std::memory_order_acquire);
std::cout << payload << '\n';
producer.join();
}
Result
42
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.