What is a semaphore?

Why Interviewers Ask This

Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid Operating Systems basics — a prerequisite for any developer role.

Answer

A semaphore is a synchronization primitive invented by Dijkstra that uses an integer variable to control access to shared resources among multiple threads. It supports two atomic operations: wait() / P() / down(): while (semaphore <= 0); // Wait if no resources semaphore--; // Acquire resource. signal() / V() / up(): semaphore++; // Release resource, wake waiter. Both operations must be atomic (no interruption between check and modify). Types: (1) Binary semaphore (counting = 0 or 1): essentially a mutex lock. Initialized to 1. wait() decrements to 0 (locks). signal() increments to 1 (unlocks): // Thread A: wait(sem); // Critical section signal(sem);; (2) Counting semaphore: value can be any non-negative integer. Initialized to N (N permits). Used to limit concurrent access to N instances of a resource: Semaphore parkingSpots = new Semaphore(10); // 10 spots // Thread (car): parkingSpots.acquire(); // Wait for a spot useParking(); parkingSpots.release(); // Free the spot. Semaphore vs mutex: mutex has ownership (only owner can release); semaphore has no ownership concept (any thread can signal). Semaphore is more general. Producer-consumer with semaphores: empty = Semaphore(N); // Buffer slots available full = Semaphore(0); // Filled slots mutex = Semaphore(1); // Mutual exclusion Producer: wait(empty); wait(mutex); produce(); signal(mutex); signal(full); Consumer: wait(full); wait(mutex); consume(); signal(mutex); signal(empty);.

Pro Tip

Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Operating Systems codebase.