Originally Posted by
Elysia
The thing is that the processor registers are much faster than memory, so the compiler sometimes tries to optimize by storing a value or variable in a register instead of reading/writing to memory. Of course, this has its own set of problems as well, since other threads, for example, can't modify that variable then, because each thread has its own set of processor registers.
The keyword volatile tells the compiler that an external process, the OS or another thread might modify this variable and thus, the compiler cannot optimize it by storing it in a register.
This may or may not be required. Usually, the compiler is smart enough to realize to or not to optimize away variables into registers when used in different threads, so the results may vary. But if you find that a thread tries to modify a variable and its value isn't changed in another thread, then you might need to add volatile to the variable.