volatile is not widely-used, but there are a few practical examples. I'll show you one.
At first, look at this.
#include <stdio.h>
#include <threads.h> // C11 threading library
int i = 0;
int noticer_thread(void *arg)
{
while (getchar() == 'a') // suppose something happened!
i = 1;
return 0;
}
int main()
{
thrd_t thrd;
int res;
thread_create(&thrd, noticer_thread, NULL);
while (i != 1) { /* wait... */ }
printf("something happened!\n");
thrd_join(thrd, &res);
}
(I've just tried C11 threading library - just practice ^o^)
Can you notice something wrong? Compiler doesn't know i will be changed by another thread, so the while loop of main can be optimized, like this -
register int EAX = i;
while (EAX != 1) { ...
Therefere, i should be volatile.
volatile int i = 0;
So, why is it practical example? In fact, I faced this kind of bug on my os-development. Suppose noticer_thread is interrupt handler, and main is kernel thread. noticer_thread set the flag which informs main of interrupt, but main couldn't know it without volatile!