I read about using the C volatile keyword in a hardware memory register, ISR, and multithreaded program.
1) register
uint8_t volatile * pReg; while (*pReg == 0) {
2) ISR
int volatile flag = 0; int main() { while(!flag) {
3) multithreading
int volatile var = 0; int task1() { while (var == 0) {
I can understand why the compiler can mistakenly optimize while in case 1), if volatile does not exist, because the change of the variable is made from hardware, the compiler may not see the change of the variable made from the code.
But for case 2) and 3), why are volatiles ever needed? In both cases, the variable is declared global, and the compiler can see that it is used in several places. So, why does the compiler optimize the while if the variable is not volatile ?
Is it because by default the compiler does not have the concept of asynchronous call (in the case of ISR) or multithreading? But this cannot be, right?
In addition, case 3) looks like a general program in multithreading without the volatile keyword. Let's say I add some lock to a global variable (the volatile keyword):
int var = 0; int task1() { lock();
For me it looks fine. So do I really need volatile in multithreading? Why have I never seen a qualifier added to a variable to avoid optimization in a multi-threaded program before ?
user1559625
source share