What is the purpose of the volatile keyword in C++? Does it provide any thread-safety guarantees?
Last updated
volatiletells the compiler a variable may change outside the program's control, so every read/write must actually happen (no register caching or elision). Legit uses: memory-mapped hardware registers and signal-handler flags (withsig_atomic_t).It gives no thread-safety: no atomicity (read-modify-write is still non-atomic) and no cross-thread memory ordering or fences.
Use
std::atomicfor concurrency. Unlike Java/C#volatile, the C++ keyword implies no memory ordering (a common interview trap).