Menu

1 / 5

The Most Dangerous Keyword in C/C++: Why volatile Is Not Atomic

DEV Community: cpp·Binary Dose·about 7 hours ago
#nzgZYCJq
#devtocpp#devto#dev#include#atomic
Reading 0:00
15s threshold

The Most Dangerous Keyword in C/C++: Why volatile Is Not Atomic

One of the most persistent myths in systems programming is the belief that declaring a shared variable as volatile makes it safe for concurrent multi-threaded access.

Consider the following multi-threaded counter:

volatile int counter = 0 ;

void worker ( ) { for ( int i = 0 ; i < 100000 ; i ++ ) { counter ++ ; // DATA RACE & LOST UPDATES! } }

Enter fullscreen mode

Exit fullscreen mode

Running two threads executing worker() concurrently will almost never result in 200,000 . Increments will be silently lost.

To understand why, we must examine the difference between Compiler Optimizations and CPU Hardware Coherence .

1. What volatile Actually Does

The volatile keyword was introduced into the C standard in 1989 for a single specific purpose: interacting with Memory-Mapped I/O (MMIO) hardware registers and asynchronous signal handlers .

It communicates one instruction to the compiler:

"Do not cache this variable inside a CPU register.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.