Acquire and release: publishing data with C11 atomics
A producer fills a message and announces that it is ready. The consumer needs more than a reliable flag value: it must also be able to access the associated ordinary data with the required ordering. A data race on ordinary C objects is not made safe by using a volatile flag. The language's atomic synchronization rules express the relationship.
The contract
In the one-shot example, the producer writes a value before a release store to a flag. A consumer that observes true with an acquire load can read that value, provided the producer does not concurrently overwrite it. This last condition is an ownership requirement, not something the acquire itself enforces. Reusing the same buffer requires a separate handoff protocol.
A small executable example
#include <stdatomic.h>
#include <stdbool.h>
#include <assert.h>
#include <stdio.h>
static atomic_bool ready;
static unsigned payload;
static void publish(void) {
payload = 42u;
atomic_store_explicit(&ready, true, memory_order_release);
}
int main(void) {
atomic_init(&ready, false);
publish();
assert(atomic_load_explicit(&ready, memory_order_acquire));
assert(payload == 42u);
puts("published value received");
}
published value received
Compiled with -Wall -Wextra -Werror and run under AddressSanitizer + UBSan.
Learning this for work or an interview? Lessons 1 and 2 of DSA for Firmware are free, with labs and C exercises. Start Lesson 1
What the example does not establish
This single-threaded host harness checks the API and logical state, not a real interleaving. On a threaded host, add tests with concurrent producer and consumer and appropriate tools for race detection. Even stress tests do not prove all execution orders. On an MCU, inspect the compiler and target's implementation, and ensure the operations are permitted in each execution context.
Checks to add in your own project
Keep normal-memory synchronization separate from memory-mapped device registers and DMA coherency. Hardware can have visibility requirements beyond the C abstract machine. A review should identify the publication point, lifetime of the published data, reuse acknowledgement, and what happens if the consumer is delayed. If you cannot state those conditions clearly, the design needs more work before optimizing memory orders.
DSA for Firmware teaches it one real bug at a time.
- 28 lessons, each starting from a real firmware bug.
- 110 C exercises with tests, and a reference solution for every one.
- Lessons 1 and 2 are free. No sign-up.
Get the next article by email
One short email when a new article or free lesson is published. No spam. Unsubscribe at any time by replying to any email. See the privacy policy.