Is it possible to interrupt the copy process of a struct by an interrupt in embedded C?
Yes. Pretty much everything in an MCU can be interrupted by an interrupt request. When the interrupt handler completes the previous code will just continue so it is usually not a problem.
In a special case the interrupt handlers can be interrupted themselves by interrupts of higher priorities (nested interrupts).
If a series of instructions must not be interrupted then you need to implement a critical section (basically globally disable interrupts, do the job, enable again).
Remember that depending on architecture of the target CPU a single line of C can be compiled to many assembly instructions. A simple i++
on an AVR is compiled to multiple instructions if i
is for example uint32_t
.
Any operation that is not atomic can be interfered with by an interrupt. This kind of programming is often very different than most other programming and can be confusing to people who haven't studied processor design or computer architecture.
You may think to yourself "This will never actually happen, how long does this code take to copy and how likely is an interrupt?" But with most production embedded applications it will happen because the product is on for years without updates.
The other issue with struct copies like this is when they do happen they are extraordinarily difficult to debug because they only happen when the interrupt occurs at just the right time (which can be as little as one cycle).
The whole point of interrupts is that they can (and do) happen all the time, and are designed to have zero impact on any code that happens to be running when they occur. All the registers are saved, and depending on the CPU architecture, a completely different register set may be swapped in, the interrupt does its thing, and then the original registers are restored and the code continues to run as normal.
Problems can occur when the interrupt service routine itself tries to access memory that is being accessed by the running, interrupted code. Even more subtle errors can occur when a time-critical I/O process is interrupted. These problems are commonplace with older, simpler, less secure architectures where there may be little separation between "user" and "supervisor/kernel" mode code.
This kind of problem can be hard to identify, and often difficult to reproduce, but once identified they're often fairly trivial to fix using defensive programming, mutexes/semaphores or simply by disabling interrupts in critical sections of code.
The general class of problems has been studied extensively, and modern multi-core CPUs and even multi-tasking operating systems would not be possible if multiple solutions were not already tried and tested.