Electronic – Mutex in interrupts


For a small micro controller without an OS what is the proper way to share data between different interrupts and the main loop?

With an OS one can just create a mutex for each critical part and carry on and the scheduler will switch between tasks for example.

If a mutex is used in an interrupt it will just lock forever so obviously this cannot work.

A simple approach I can think of can be to have copies of the variables in a table and when they are modified set a flag for each variable modified. Then in the main loop disabling interrupts copy the copies to the main variables and viceversa (with a system of priorities in case two or more were changed). This would take quite some time and but it should work.

Best Answer

There are several ways:

  1. Make each piece of state small enough to be updated atomically by the hardware. For example, if you're on a 16 bit machine (like a Microchip dsPIC, for example), then make each piece of shared state no more than 16 bits.

  2. Use FIFOs between interrupt and foreground code. There are ways to design FIFOs so that no mutex is needed, but foreground and interrupt code can still access their ends at any time.

  3. Have the foreground code temporarily shut off interrupts around accesses to critical shared data that is not atomically updated.