I was reviewing RTOS concepts and had a question about shared resource access.
If multiple tasks access a shared resource (like a global variable or hardware peripheral) without protection (mutexes, semaphores, etc.), how exactly does data corruption occur? Does it depend on the scheduler’s behaviour, or are there other factors (like interrupts )?
The basic form of corruption can occur when a sequence of operations that are assumed to be consecutive and uninterrupted get interrupted. For instance, incrementing a variable. This would often be done with 3 instructions, one to read the current contents into a CPU register, a second to increment that register, and a third to write that answer back.
If two Tasks, or a Task and an ISR are both going to do this, and an interrupt occurs after the first instruction (the read) but before the last instruction (the write), the the second operation set of code will still see that same original value, and increment it, and then when the first code gets resumed, it will right its incremented value, and that will be one less then exected, as both were supposed to increment it.