volatile for variable that is only read in ISR?

前端 未结 2 696
忘了有多久
忘了有多久 2021-01-23 20:25

Is volatile needed for a variable that is read&write in main loop, but read-only in ISR?

EDIT: At the moment of writing in main, the ISR is disabled. S

2条回答
  •  轮回少年
    2021-01-23 21:01

    Is volatile needed for a variable that is read&write in main loop, but read-only in ISR?

    volatile is not the issue here, as much as insuring main loop's writes are not broken apart.

    Any changes in main() without protection from an ISR call, can lead to problems, volatile or not. Declaring it volatile does not save code from that issue.

    volatile some_type obj;
    
    void ISR() {
      foo(obj);
    }
    
    int main() {
      for (;;) {
        // volatile useful here to prevent the assignment from being optimized away.
        some_type tmp = bar();
    
        // protect from potential interruption need here.
    
        // Without protection, ISR(), 
        // doesn't know it is working with a completely written `obj`
        obj = tmp;
    
        // release from potential interruption
    }
    

    volatile is useful in both directions, for main() to know ISR() may have changed obj and for main() to not optimize away assignments.

    Yet since ISR() does not change obj, so volatile is not needed.

    Declaring obj atomic may help - but that is another question.

提交回复
热议问题