I’m working on a homework problem out of Stalling’s Operating Systems: Internals and Design Principals. As such, I am not requesting an answer but any help understanding this would be helpful as I am having a tough time wrapping my head around this one. There are two processes executing:
Both processes are executing the following code:
shared int x;
x = 10;
while (1)
{
x = x - 1;
x = x + 1;
if (x != 10)
printf(“x is %d”,x)
}
The first part of this question asked how “x is 10” could be printed, which I had no trouble tracing the logic for.
However, the second part asks how can “x is 8” be printed. Additionally it gives the hint:
“You should remember that the increment/decrements at the source language level are not done atomically, that is, the assembly language code:”
LD r0,X
INCR r0
STO r0,X
“implements the single C instruction x=x+1”
Despite the hint, I am having trouble seeing how a process can ever reach the printf section without the value being incremented back up to at least 9. What am I missing?
Like this:
The lesson here is that if an operation is not atomic, then writes can be lost if they get overwritten.