CodePark/ questions / Concurrency primitives & race conditions
START PRACTICINGPRACTICE
Backend question · OS, networking & Linux › Concurrency primitives & race conditions

Which statement correctly describes the difference between a mutex and a counting semaphore?

A mutex admits one holder and is unlocked by the thread that locked it; a counting semaphore keeps a counter and admits up to N holders at once

A mutex gives mutual exclusion with ownership. Only one holder can have it at a time, and the thread that locked it is the one that unlocks it.

A
counting semaphore keeps a counter:
•
wait lowers the counter by one. If the counter is zero, the caller blocks (waits).
•
post raises the counter by one.
• Any thread may call
post, not only the one that called wait.

This makes a semaphore good for limiting work to N at once, like a pool of 10 database connections.


"A mutex works only between processes, and a semaphore works only between threads" is wrong: both kinds exist for threads and for processes. "A semaphore initialised to 5 guarantees that exactly 5 threads are always running" is wrong: 5 is a maximum, not a guarantee. "A mutex never blocks" is wrong: a mutex blocks a thread that tries to take it while another thread holds it.