← Lessons

quiz vs the machine

Platinum1810

Concurrency

The Volatile Keyword Misconceptions

Why volatile prevents some optimizations but not data races.

5 min read · advanced · beat Platinum to climb

The Volatile Keyword Misconceptions

The volatile keyword is one of the most misunderstood tools in concurrency. In languages like C and C plus plus, volatile tells the compiler that a variable may change outside the normal flow, so it must not cache the value in a register and must not elide reads or writes.

That sounds like a synchronization tool, but it is not. Volatile gives no atomicity and no memory ordering across threads. A volatile increment is still read add write and can lose updates. Two volatile writes by one thread may still be reordered as seen by another thread, because volatile does not insert the fences that acquire release ordering does.

  • What it does Prevents the compiler from caching or removing accesses, useful for memory mapped hardware registers.
  • What it does not do It does not make operations atomic and does not establish happens before order between threads.
  • The right tool For sharing data between threads, use atomics with explicit ordering or a lock, not volatile.

The confusion comes partly from Java, where volatile was redefined to carry acquire release semantics. In C family languages it does not, so relying on it for thread communication is a classic and dangerous bug.

Key idea

In C family languages volatile only stops the compiler from caching accesses, it provides neither atomicity nor cross thread ordering, so it is not a synchronization primitive.

Check yourself

Answer to earn rating on the learn ladder.

1. What does volatile guarantee in C and C plus plus?

2. What should you use to share data between threads instead of volatile?