Electronic – AVR diagram of functions calling, ISR and main loop share the same resource

atmegaavrinterrupts

I made a simple diagram of functions calls to illustrate the potential problem which bothering me a little. As you can see, my task_list (which is simple linked list) is modified either in ISR and program main loop.

  • Can this solution cause errors in the future?
  • What kind of errors?
  • Should I use some kind of synchronization/resource protection solutions to prevent errors?
  • What kind of synchronization?

enter image description here

Best Answer

Yes, whenever a data structure such as your task list can be accessed (modified or viewed) by more than one process, it is essential that any changes to that data structure be complete and self-consistent when viewed by any one process. This is in general called "atomic update".

A linked list is a nontrivial data structure, and updates to it require more than one machine instruction to accomplish. If the ISR interrupts the main loop when it happens to be updating the list, the ISR won't see a consistent structure. If the ISR then tries to update the list itself, chaos ensues.

One simple way to protect access to shared data is through mutual exclusivity (or "mutex" for short). In the case of a main loop vs. ISR conflict, this is easy to accomplish by means of the interrupt enable flag.

  • If the ISR wants to update the structure, it has exclusive access, because by definition, no other process can run until it exits.
  • If the main loop wants to update the structure, it must disable interrupts first, and then re-enable them when it is finished.

If more than one non-interrupt process wants to access the structure, you can add a binary flag to control access to the data structure, and this flag can be set by only one process at a time. However, note that updates to this flag must also be atomic, which again means disabling interrupts, so that a task switch does not occur between testing and setting the flag.