Where all to use volatile keyword in C

前端 未结 5 1684
余生分开走
余生分开走 2021-01-20 04:37

I know volatile keyword prevents compiler from optimizing a variable and read it from memory whenever it is read. Apart from memory mapped registers, what are all the situat

5条回答
  •  长发绾君心
    2021-01-20 05:10

    In neither of your examples is volatile necessary.

    volatile is necessary:

    1. anywhere a variable may be changed outside of the control of a single thread of execution,
    2. anywhere the variable access is required to occur even when it semantically has no effect.

    Case 1 includes:

    • memory mapped I/O registers,
    • memory used for DMA transfers,
    • memory shared between interrupt and/or thread contexts,
    • memory shared between independent processors (such as dual port RAM)

    Case 2 includes:

    • loop counters used for empty delay loops, where the entire loop may otherwise be optimised away completely and take no time,
    • Variables written to but never read for observation in a debugger.

    The above examples may not be exhaustive, but it is the semantics of volatile that are key; the language only has to perform an explicit access as indicated by the source code.

提交回复
热议问题