Course contentsShow
← Computer Science
Lesson 1301 of 2,87230. Process SynchronizationFree lesson

Resource Counting with Counting Semaphores

Managing pools of identical resources using counting semaphores initialized to resource count.

Resource Counting with Counting Semaphores

What you'll learn: How to use counting semaphores to manage a fixed pool of identical resources fairly and safely in concurrent programs.

The Core Idea

Imagine a parking lot with exactly 5 spaces. When cars arrive, you need to track how many spots remain. Counting semaphores solve this exact problem for computing resources like database connections, buffer slots, or printer access.

A counting semaphore is initialized to the number of available resources. Each wait() operation decrements the count (claiming a resource), and each signal() operation increments it (releasing a resource back to the pool). When the count reaches zero, threads attempting wait() block until someone calls signal().

How It Works in Practice

Let's say you have 3 database connections to share among multiple threads:

sem_t db_connections;
sem_init(&db_connections, 0, 3);  // Initialize to 3 available resources

When a thread needs a connection:

sem_wait(&db_connections);  // Decrement count; blocks if count is 0
// Use database connection safely
sem_post(&db_connections);  // Increment count, releasing resource

The semaphore automatically handles the bookkeeping. If all 3 connections are in use, the 4th thread blocks at sem_wait() until another thread calls sem_post().

Why This Matters

Without counting semaphores, you'd need complex manual tracking with locks and condition variables. The semaphore elegantly combines:

  • Resource counting (how many are free?)
  • Mutual exclusion (atomic increment/decrement)
  • Blocking/waking (sleep when empty, wake when available)

This pattern appears everywhere: memory pools, thread pools, network connections, and I/O channels.

Key Takeaway: Counting semaphores manage pools of N identical resources by maintaining an atomic counter—threads block when resources are exhausted and automatically wake when resources become available again.