Bird
Raised Fist0

A developer wrote this pseudocode for two threads incrementing a shared counter:

medium📝 Analysis Q6 of Q15
LLD - Design — Parking Lot System
A developer wrote this pseudocode for two threads incrementing a shared counter:
Thread 1:
lock.acquire()
counter += 1
lock.release()

Thread 2:
lock.acquire()
counter += 1
lock.release()
But the counter sometimes ends up incorrect. What is the likely mistake?
AUsing the same lock object for both threads
BNot acquiring the lock before incrementing
CReleasing the lock before incrementing
DLock object is not shared between threads
Step-by-Step Solution
Solution:
  1. Step 1: Analyze lock usage

    Both threads acquire and release a lock around increment, which is correct if the lock is shared.
  2. Step 2: Identify cause of incorrect counter

    If the lock object is not shared, each thread locks independently, causing race conditions.
  3. Final Answer:

    Lock object is not shared between threads -> Option D
  4. Quick Check:

    Shared lock needed for correct synchronization [OK]
Quick Trick: Ensure lock object is shared among threads [OK]
Common Mistakes:
MISTAKES
  • Assuming separate locks synchronize threads
  • Not acquiring lock before critical section
  • Releasing lock too early

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes