‹ All Operating Systems questions

Operating Systems Practice Question 10: Counting Semaphore Pool

Operating Systems · Test 1 · question 10 of 10

Concurrency & Synchronizationeasy

A web server has 50 worker threads that share a pool of 5 database connections. At most 5 threads may hold a connection at once; a sixth thread asking for one should block until another thread returns its connection.

Which synchronization primitive fits this limit most directly?

Select one answer
Show answer and explanation

Answer:

  • D. A counting semaphore initialized to 5, waited on before use and posted after release

A semaphore is an integer that never falls below zero. sem_wait() decrements it, blocking if the value is currently zero, and sem_post() increments it, waking a waiter. Its initial value sets the behaviour: initialized to 5, the first five waits succeed immediately, the sixth blocks, and each post after a connection is returned lets one more thread in. That maps directly onto "at most 5 at once".

Option A is wrong: a mutex allows exactly one holder, so only one thread could use the pool at a time and four connections would sit idle.

Option B is wrong: a spinlock is also a one-holder lock, and spinning burns CPU while waiting instead of blocking. It does not count available connections.

Option C is wrong for the same reason as A: a semaphore initialized to 1 is a binary semaphore that acts like a lock, admitting one thread at a time. The initial value must equal the number of connections.

References: sem_overview(7) - Linux manual page; OSTEP - Semaphores

Practice Test 1 ›