How do you publish data safely between two threads using C11 atomics?
Short answer: Publish a ready flag with release semantics after writing data. A reader that observes the publication using an acquire load can then safely access the published data.
#include <stdatomic.h>
static int data;
static atomic_int ready = 0;
void producer(void)
{
data = 100;
atomic_store_explicit(&ready, 1, memory_order_release);
}
int consumer(void)
{
if (atomic_load_explicit(&ready, memory_order_acquire))
return data;
return -1;
}
Producer Consumer
data = 100 load ready (acquire)
store ready (release) ---> if ready == 1: read data
Why: If the acquire load reads the release store, the producer's preceding write happens-before the consumer's read.
Limitation: This is one-time publication. Reusing the buffer concurrently requires a separate ownership protocol or lock. Volatile alone is not sufficient.
Interview takeaway: Acquire/release creates a synchronization relationship without requiring sequential consistency for every operation.
One-time publication versus repeated communication
Producer: data = 100
release-store ready=1
|
synchronizes-with
v
Consumer: acquire-load ready reads 1
read data -> 100
This example assumes a single publisher, immutable data after publication and no concurrent reset. If the producer writes data again while a consumer is reading, the atomic flag alone does not prevent a C data race. For repeated messages, use a queue, mutex, or an ownership handshake with acknowledgment before reusing the payload. A relaxed flag does not establish the required happens-before relationship. On ARM64, acquire/release accesses commonly compile to LDAR/STLR or equivalent sequences.