Question Bank

Producer / Consumer and Locks

Difficulty: Medium

Mid-tier drills on bounded buffers, mutexes, semaphores, and deadlock detection. Code stems in Python and JavaScript; one trace involves the four conditions for deadlock.

Question Bank
/

Producer / Consumer and Locks

Producer / Consumer and Locks

Mid-tier drills on bounded buffers, mutexes, semaphores, and deadlock detection. Code stems in Python and JavaScript; one trace involves the four conditions for deadlock.

Question Bank
Medium
JavaScript
Python
5 questions
concurrency
pessimistic-locking
multithreading
interview-prep

1,174 views

20

Implement a bounded-buffer producer / consumer with a Python threading.Condition. The buffer has capacity 4. Producer waits when full; consumer waits when empty.

Examples

Example 1:

Input: BoundedBuffer(capacity = 4); producer thread calls put four times then a fifth time
Output: the first four puts succeed; the fifth blocks until a consumer's get notifies
Explanation: Use a single Condition guarding both 'not full' and 'not empty'. put waits while len(buf) == capacity in a while loop (never if, to handle spurious wake-ups), appends, then notify_all so a sleeping consumer can re-check.