c / intermediate
Snippet
Ensuring Visibility with volatile
The 'volatile' qualifier tells the compiler that a variable's value can change at any time without any action being taken by the code nearby. This prevents the compiler from optimizing the variable by caching it in a register, which is crucial for hardware-mapped I/O or shared memory.
snippet.c
c
1
2
3
4
5
6
7
8
9
10
#include <stdio.h>void wait_for_event() {volatile int flag = 0;// Imagine flag is changed by an interrupt or hardwarewhile (flag == 0) {// Busy wait}printf("Event occurred!\n");}
Breakdown
1
volatile int flag = 0;
Defines a variable that the compiler must always reload from memory.
2
while (flag == 0)
The compiler will not optimize this into an infinite loop if flag isn't changed in this thread.