Bird
0
0

Consider this pseudocode for a shared counter increment:

medium📝 Analysis Q13 of 15
LLD - Advanced LLD Concepts
Consider this pseudocode for a shared counter increment:
lock.acquire()
counter = counter + 1
lock.release()
print(counter)
If two threads run this code simultaneously starting with counter = 0, what is the possible output?
A0
B3
C2
DAny number greater than 2
Step-by-Step Solution
Solution:
  1. Step 1: Understand lock usage in code

    The lock ensures only one thread increments the counter at a time, preventing race conditions.
  2. Step 2: Calculate final counter value

    Two threads each increment once, so counter goes from 0 to 2 safely.
  3. Final Answer:

    2 -> Option C
  4. Quick Check:

    Lock ensures increments are safe, so counter = 2 [OK]
Quick Trick: Locks prevent lost updates, so increments add up [OK]
Common Mistakes:
  • Ignoring lock and assuming race condition
  • Thinking output can be 0 or 1 due to concurrency
  • Assuming counter can exceed 2 without loops

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes