Process Coordination & Semaphores

Why does this race condition occur if each of the statements is an independent instruction?

The answer is that - it is not quite true. On the hardware level, every instruction consists of actually three steps: (1) fetch counter from memory into a register, (2) increment or decrement the register, and (3) store the new value of counter back to memory.

If the instructions from the two processes get interleaved, the result of the execution of the instructions is unpredictable (as the figure on the following slide shows,) and depends on when the instructions are executed by the operating system. Race conditions are notoriously difficult to identify and debug, because by their very nature they only occur on rare occasions, and only when the timing is just exactly right.

The solution is to only allow one process at a time to manipulate the value inside counter, and we will see several ways of achieving this.