1. LPU MCA Semester 1
  2. CAP366
  3. Unit 5

CAP366 · Unit 5: Process synchronization

Synchronization background and race conditions

10 practice questions · in the MTE and ETE syllabus

Key points

  • Race condition: result depends on access order
  • counter++ is load, modify, store
  • Races occur on a single CPU too
  • Critical section = code touching shared data

When cooperating processes share data, an uncontrolled interleaving can give wrong results: a race condition occurs when the outcome depends on the order of access.

Example: counter = 5. counter++ compiles to load r1, add 1, store; counter-- to load r2, subtract 1, store. Interleaving: r1 = 5, r1 = 6, r2 = 5, r2 = 4, store 6, store 4 leaves counter = 4. Possible final values are 4, 5 or 6 (5 only if the updates do not overlap).

Code structure: entry section, critical section, exit section, remainder section.

ConditionRace possible?
Two writers to shared dataYes
One writer, one readerYes
Only readers of a constantNo

Exam pitfall: races exist even on a single CPU because the scheduler can preempt a process between the load and the store; they do not need multiple cores.

Try two questions

Question 1 · Tier 5, Exam level

Which statement about race conditions is correct?

  1. They can occur on a single CPU because preemption may interleave a non-atomic update
  2. They need at least two CPU cores, since an interleaving requires truly parallel execution
  3. They disappear when the program is compiled with optimisation turned on
  4. They occur when several processes read the same shared data but none of them modifies it
Show the answer

A. A timer can preempt a process between the load and the store, so even one CPU can interleave updates. Two cores are not required, and read-only sharing is harmless.

Question 2 · Tier 3, Apply

counter = 10. A producer runs counter++ as P1 r1 = counter; P2 r1 = r1 + 1; P3 counter = r1. A consumer runs counter-- as C1 r2 = counter; C2 r2 = r2 - 1; C3 counter = r2. The steps run in the order P1, C1, P2, C2, C3, P3. What is the final value of counter?

  1. 11
  2. 9
  3. 10
  4. 12
Show the answer

A. Both read 10; the consumer stores 9 and then the producer stores 11 which overwrites it, leaving 11.

Why not B: This would result if the consumer's store came last.

Why not C: This is the value with correct synchronisation.

Why not D: No interleaving of these steps can give 12.