What is the danger in using shared memory?

Embedded C interview Question

What is the danger in using shared memory?

Answer

Data corruption is a critical issue while we use shared memory. Have a look at the following example

Mainline code:
1. Read variable X into register
2. Decrement register contents
3. Store result back at variable X

ISR code:
A. Read variable X into register
B. Increment register contents
C. Store result back at variable X

Let's say that the shared variable X is tracking the number of bytes in a buffer. The ISR puts a byte into the buffer and increments X. The mainline code reads a byte from the buffer and decrements X. Say that X starts out with a value of 4. The ISR puts a byte into the buffer and increments it to 5. The mainline code then reads a byte and decrements the count back to 4.

But if an interrupt occurs between lines 1 and 3 in the mainline code, the value of X will be corrupted. First, the mainline code reads X, which is 4, into a register. Then the ISR occurs, also reads 4, and increments X to 5. After the ISR completes, the mainline code finishes, storing the improper value 3 in X.