Bird
0
0

Consider this pseudocode for two threads incrementing a shared counter without locks:

medium📝 Analysis Q13 of 15
LLD - Design — Parking Lot System
Consider this pseudocode for two threads incrementing a shared counter without locks:
Thread 1: temp = counter
          temp = temp + 1
          counter = temp

Thread 2: temp = counter
          temp = temp + 1
          counter = temp
What is the possible final value of counter if it starts at 0?
A2
BAny negative number
C1
D0
Step-by-Step Solution
Solution:
  1. Step 1: Analyze concurrent increments without locks

    Both threads read the same initial value 0, increment it to 1, and write back 1, causing one increment to be lost.
  2. Step 2: Determine final counter value

    Because of race condition, the counter may only increase once, resulting in final value 1 instead of 2.
  3. Final Answer:

    1 -> Option C
  4. Quick Check:

    Race condition causes lost update = 1 [OK]
Quick Trick: Without locks, increments can overwrite each other [OK]
Common Mistakes:
MISTAKES
  • Assuming both increments always succeed
  • Ignoring race conditions
  • Thinking counter can be negative here

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes