Synchronization Primitives

Mutexes, reentrant locks, semaphores, condition variables, read-write locks, barriers and events: what each one answers, how it behaves in Python and Java, and a running test for each.

Overview

A synchronization primitive is a small object that threads use to coordinate: to take turns on shared data, to limit how many run at once, or to wait until something has happened. Every higher-level tool, from a blocking queue to a thread pool, is built from a few of them.

Interviewers test whether you pick the right one and use it correctly. Most bugs come from using a good primitive the wrong way: waiting on a condition with if instead of while, releasing a semaphore twice, or taking a lock that is already held by the same thread.

Pick by the question you are asking

Start from the question your code is asking, and the primitive follows. Each one below names the Python and Java classes that provide it.

  • Only one thread at a time in this code? Use a mutex (lock): threading.Lock in Python; synchronized or ReentrantLock in Java.
  • May the same thread take it again? Use a reentrant lock: threading.RLock in Python; ReentrantLock or synchronized in Java.
  • At most N threads at a time? Use a counting semaphore: Semaphore(n) or BoundedSemaphore(n) in Python; Semaphore in Java.
  • Wait until some state is true? Use a condition variable: threading.Condition in Python; Condition or Object.wait in Java.
  • Many readers or one writer? Use a read-write lock: none in the Python standard library; ReentrantReadWriteLock or StampedLock in Java.
  • Wait until all N threads arrive? Use a barrier: threading.Barrier in Python; CyclicBarrier in Java.
  • Wait for a one-time signal? Use an event or latch: threading.Event in Python; CountDownLatch in Java, which is one-shot.

The sections below take them in that order, starting with the plain lock.

Interview questions

  • What is the difference between a mutex and a semaphore?
  • When should you use a condition variable instead of polling?
  • What is a read-write lock, and when would you use one?
  • Implement a counting semaphore using only a mutex and a condition variable.
  • What is a reentrant lock, and when does reentrancy matter?

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio