Search code examples
creal-timeinterruptmultitaskingrtos

Identifying possibility of interference


In multi tasking environment. If a task has the expression y = x + x; is there a possibility of an interrupt(task switching) occurring between the two reads of x.


Solution

  • In most cases a compiler generate code would read x only once since the optimisation is trivial. In fact it might even translate the operation into a right-shift, equivalent to x << 1. However you cannot guarantee that, and if x were declared volatile it would necessarily make two reads that will then be uninterruptible between reading of the low-order and high-order words (or vice versa),and in that case the assignment of y is also interruptable.

    Another issue is that if x were not an atomic data type (i.e. could not be read in a single instruction) such as a 32 bit type on a 16 bit target for example, then even if it were a single read, it may be interruptable.

    In either case it is only normally a problem if the x itself (or y in the second case) is shared between contexts (in which case it should also be declared volatile so two reads would then be necessary), or if for some reason the timing of the assignment were somehow critical and needed to be entirely deterministic (unlikely).

    If x is shared and therefore volatile but is an atomic type, the simple solution in this example is to write the expression y = x << 1 or y = x * 2 to ensure that x is read only once. Where x is not atomic - you might need to lock the scheduler or disable interrupts (i.e. use a critical section), or more selectively protect the access with a mutex for example. For more complex expressions where the expression cannot be reduced to a single reference to the shared variable, simply assigning the variable to a non-shared local temporary variable ensures that it is read just once. The issue of atomicity still stands.