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.
import threading
from collections import deque

class BoundedBuffer:
    def __init__(self, capacity=4):
        # TODO: store capacity, a deque, and a Condition
        pass
    def put(self, item):
        # TODO: wait while full, then append and notify
        pass
    def get(self):
        # TODO: wait while empty, then popleft and notify
        pass