In a producer-consumer system with a fixed-size buffer, which semaphore usage pattern ensures that producers block when the buffer is full and consumers block when the buffer is empty, while allowing safe concurrent access?
easy💻 Programming Q1 of Q15
Operating Systems - Producer-Consumer Problem Using Semaphores
In a producer-consumer system with a fixed-size buffer, which semaphore usage pattern ensures that producers block when the buffer is full and consumers block when the buffer is empty, while allowing safe concurrent access?
AUse a single binary semaphore to control both producer and consumer access to the buffer.
BUse two counting semaphores: one for tracking empty slots and one for full slots, plus a mutex for mutual exclusion.
CUse only a mutex lock without any counting semaphores to synchronize producers and consumers.
DUse a counting semaphore initialized to zero for both producers and consumers.
Step-by-Step Solution
Solution:
Step 1: Use two counting semaphores
One semaphore counts empty slots (initialized to buffer size), the other counts full slots (initialized to 0).
Step 2: Use a mutex
Mutex ensures mutual exclusion when accessing the buffer to prevent race conditions.