volatile Volatile object qualifier
volatile Volatile object qualifier
volatile suits device registers. Signal-handler sharing requires volatile sig_atomic_t, not any volatile object. It gives no atomicity or synchronization.
| Category | Type qualifiers |
|---|---|
| Kind | Keyword / Statement |
| C standard | C89 / C90 |
📝 Syntax
volatile int flag;
▶ Example
Edit the C code below and click Run; the server compiles and executes it:
Output:
status = 1, attempts = 1
ℹ️ Info The original unbounded wait is now a bounded loop: update_status sets status to 1 on the first pass, so attempts is always 1. This function only simulates a status update; it does not present volatile as real thread synchronization.
🏷️ Related type qualifiers
📚 Related Tutorials
❓ FAQ
QCan volatile replace atomic operations for thread safety?
ANo. volatile provides no atomic read-modify-write, mutual exclusion, or inter-thread happens-before relationship. Shared mutable state should use C11 atomics with suitable memory ordering, or mutexes.
QDoes volatile prevent the compiler from performing all optimizations?
ANo. It constrains accesses to volatile objects so that they actually occur and are ordered as required by the abstract machine; other computations can still be optimized. It does not mandate a particular CPU cache instruction for every access.
QCan the volatile flag-waiting example hang forever?
ANo. The loop attempts at most three passes, and update_status writes 1 on the first, making the condition false. Real hardware polling should still include a timeout and use the platform's prescribed register-access method.