Operating Systems Medium coding 1 views 1 min read

Implement the bounded buffer producer-consumer problem using semaphores.

Peer-reviewed by HireXTech Technical Panel Updated for 2025/2026 hiring Editorial standards
Practise this track
Interviewer Expectations for this Question
01
Core Competency

Assesses fundamental understanding of Operating Systems conventions, runtime behavior, and memory/performance considerations.

02
Evaluation Criteria

Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.

Comprehensive Model Answer Verified Solution

The bounded buffer is solved with one mutex plus two counting semaphores, empty and full.

sem_t empty, full;
pthread_mutex_t m;
buffer[N]; int head, tail;

void put(item x) {
    sem_wait(&empty);
    pthread_mutex_lock(&m);
    buffer[tail] = x;
    tail = (tail + 1) % N;
    pthread_mutex_unlock(&m);
    sem_post(&full);
}
void get(item *x) {
    sem_wait(&full);
    pthread_mutex_lock(&m);
    *x = buffer[head];
    head = (head + 1) % N;
    pthread_mutex_unlock(&m);
    sem_post(&empty);
}

empty counts free slots, full counts filled slots, and the mutex protects the buffer and indices. Signal after unlocking so a waiter does not wake and immediately block on the mutex. Initialise empty to N and full to 0. Swapping the wait order, or holding the mutex while waiting on a semaphore, risks deadlock.

Candidate Response Strategy & Interview Tips

  1. Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
  2. Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
  3. Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
  4. Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.
Related Topics & Skills
Spotted an error or have an alternative solution?