Volatile vs atomic in embedded C: different contracts
Consider a foreground task and a background task that both count completed messages. A declaration that tells the compiler the value may change unexpectedly does not make increment a single indivisible action. The read, calculation and write still constitute an update that can overlap another update. This is a language-level concern even before you inspect the assembly.
The contract
An atomic object accessed by C11 atomic operations has a different contract. The relaxed ordering below is sufficient for an independent count when the value does not publish any other data. A release/acquire pair has a different purpose: it can establish ordering for associated memory when the acquire observes the appropriate release. Do not treat relaxed operations as a way to publish an unrelated buffer.
A small executable example
#include <stdatomic.h>
#include <assert.h>
#include <stdio.h>
int main(void) {
atomic_uint completed;
atomic_init(&completed, 0u);
unsigned previous = atomic_fetch_add_explicit(&completed, 1u, memory_order_relaxed);
assert(previous == 0u);
assert(atomic_load_explicit(&completed, memory_order_relaxed) == 1u);
puts("atomic counter: 1");
}
atomic counter: 1
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
The example runs in a single host thread, so it demonstrates the interface and return value, not a stress test of concurrency. On an MCU, confirm whether the chosen atomic width is lock-free, whether the compiler supports the required interrupt context, and whether a library call or interrupt masking is involved. An atomic operation intended for normal memory must not be assumed safe for a memory-mapped peripheral. Consult the register documentation for that operation.
Checks to add in your own project
A useful review asks who writes the object, who reads it, what memory is being published, and which execution contexts may interrupt each other. Test counter rollover separately if the count has a defined range. If a critical section is the correct target-specific solution, measure its effect on interrupt latency rather than substituting a qualifier.
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.