I read about usage of C volatile
keyword in memory-mapped hardware register, ISR, and multithreaded program.
1) register
uint8_t volat
The compiler is indeed to allow that nothing else changes your variables unless some every specific conditions are met. One of them is volatile access; others are certain compiler barriers.
The naive way to program multithreaded code which you may have in mind is indeed prone to errors and would be considered undefined behaviour. If you have correct multithreaded code, then either an optimisation is still legal (like in your final task1
, where the loop is still UB and may be thrown out), or the synchronisation primitives will contain the necessary barriers (usually in the guts of some atomic variables).
To round things up, here's a corrected version of the multithreaded example:
for (;;)
{
lock();
if (var != 0) { unlock(); break; }
unlock();
}
The implementation of the unlock()
function introduces a compiler barrier which ensures that the loop cannot be optimized away.