Search code examples
cinterruptvolatile

volatile for variable that is only read in ISR?


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. So, the variable is effectively used atomically.

EDIT: (Very much related):

volatile vs memory barrier for interrupts


Solution

  • volatile is a bad way to synchronize access. It is an optimization barrier but not more.

    • it is not atomic; e.g. when your some_type is uint64_t on a platform without native 64 bit datatypes, there might be read only a part. E.g.

      main()                  irq()
      
      /* initialization */ 
      var[0..31]  = 4
      var[32..63] = 8
      
      /* modificatoin */ 
      var[32..63] = 23
                            /* read */
                            a_hi = var[32..64] = 32
                            a_lo = var[0..31]  = 4
      var[0..31] = 42
      
    • depending on architecture, there might be needed memory barrier operations. E.g. when main and irq runs on different cores which have dedicated caches, the irq will never see the updated value

    The first problem requires locking but locking operations usually imply an optimization barrier, so that volatile is superfluously.

    Ditto for the second problem where memory barriers act as an optimization barrier too.

    volatile is useful for implementing access to processor memory (which might change between two reads or have side effects when writing). But usually, it is unneeded and too expensive.