Interview frequency: …
Short answer
A Mutex is an exclusive lock owned by one thread. A Semaphore allows up to N concurrent threads. A Spinlock busy-waits without putting the thread to sleep. A Read-Write Lock permits multiple readers or a single writer.
Explanation
If a critical section is extremely short (a few nanosecond-scale instructions), a Spinlock can be useful because it avoids the context-switch cost of sleeping and waking a thread. For a limited resource, such as a database connection pool with 10 connections, a counting Semaphore is ideal. If code reads data thousands of times and writes rarely, a Reader-Writer Lock can improve performance by allowing concurrent reads until a writer arrives.
Code example
// Mutex: Exclusive lock for one thread
mutex.lock();
try { criticalWork(); } finally { mutex.unlock(); }
// Semaphore: Allows up to five concurrent threads
semaphore.acquire();
service();
semaphore.release();Common mistakes
- Using a Spinlock on a single-core system, freezing the processor in a useless busy loop.
Follow-up questions
- How do Compare-And-Swap (CAS) algorithms and lock-free data structures work?
- What is a race condition, and what is a critical section in concurrent programming?