c - About when should we use keyword 'volatile'? -


i know basics of 'volatile' still want make clear :)

if variables in memory going modified hardware, know need use 'volatile' protect it. however, question that:

  1. if variables going modified function in same file;
  2. if variables going modified function in same project (in different files, codes may belong same thread of different threads).

do need use 'volatile'?

thanks,

volatile not widely-used, there few practical examples. i'll show one.

at first, @ this.

#include <stdio.h> #include <threads.h> // c11 threading library  int = 0;  int noticer_thread(void *arg) {     while (getchar() == 'a') // suppose happened!         = 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 tried c11 threading library - practice ^o^)

can notice wrong? compiler doesn't know i changed thread, while loop of main can optimized, -

register int eax = i; while (eax != 1) { ... 

therefere, i should volatile.

volatile int = 0; 

so, why practical example? in fact, faced kind of bug on os-development. suppose noticer_thread interrupt handler, , main kernel thread. noticer_thread set flag informs main of interrupt, main couldn't know without volatile!


Comments