_Atomic C11 atomic types
_Atomic C11 atomic types
C11 _Atomic declares atomic types; data-race safety requires correct atomic operations, not stdatomic.h alone. Compound invariants need synchronization.
| Category | Type qualifiers |
|---|---|
| Kind | Keyword / Statement |
| C standard | C11 |
📝 Syntax
_Atomic int counter = 0;
/* Or use atomic_int counter from stdatomic.h */
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
counter = 2
⚠️ Warning The example performs atomic operations sequentially in one thread, so it reliably prints 2; it does not demonstrate lock-free behavior. _Atomic supplies atomic semantics, and atomic_is_lock_free must be used to query whether a particular type is lock-free on the target implementation.
🏷️ Related type qualifiers
📚 Related Tutorials
❓ FAQ
QIs an _Atomic type always implemented without locks?
ANot necessarily. An implementation may use locks internally for atomic operations. atomic_is_lock_free queries a particular object, while ATOMIC_*_LOCK_FREE macros provide compile-time capability information for the corresponding types.
QHow does atomic_fetch_add differ from ordinary counter++?
Aatomic_fetch_add is an atomic read-modify-write that other threads cannot observe as separate steps, and it carries the applicable memory ordering. Concurrent ordinary counter++ operations on a shared object can cause a data race.
QCan an atomic counter replace every mutex?
ANo. Atomic operations cover individual atomic operations and their memory-ordering semantics. They do not automatically combine updates to multiple objects into a transaction or protect invariants spanning multiple steps.