What is a semaphore and how does it work?

Technical
Medium
Flipkart
56.9K views

This OS question focuses on a synchronization primitive used to control access to shared resources. It tests deep understanding of concurrency.

Why Interviewers Ask This

Semaphores are fundamental tools for managing concurrent access. Interviewers want to see if you understand counting mechanisms and blocking behavior. This is key for writing thread-safe code.

How to Answer This Question

Define a semaphore as a variable used to control access to a common resource. Distinguish between binary and counting semaphores. Explain P (wait) and V (signal) operations. Discuss how they prevent race conditions. Mention potential pitfalls like deadlocks.

Key Points to Cover

  • Semaphore definition
  • Binary vs counting types
  • P and V operations
  • Blocking behavior

Sample Answer

A semaphore is a synchronization tool that uses an integer value to control access to shared resources by multiple processes. Binary semaphores act like locks (0 or 1), while counting semaphores allow multiple instances. The P operation decrements the value and blocks if zero; the V operation increments it and wakes a waiting process. This mechanism ensures mutual exclusion and coordinates resource usage efficiently without busy waiting.

Common Mistakes to Avoid

  • Confusing with mutexes entirely
  • Incorrect P/V logic
  • Ignoring counting semantics

Practice This Question with AI

Answer this question orally or via text and get instant AI-powered feedback on your response quality, structure, and delivery.

Start Practicing

Related Interview Questions

Browse all 118 Technical questionsBrowse all 81 Flipkart questions