Implement the bounded buffer producer-consumer problem using semaphores.
Assesses fundamental understanding of Operating Systems conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
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
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.