_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.

CategoryType qualifiers
KindKeyword / Statement
C standardC11

📝 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 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏