progress

~/problems / Locks / Deadlock and lock ordering

Shared party playlist

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

At a party, everyone's phone adds songs to one shared playlist, and a queue screen and a DJ bot want to hear about every new song.

Implement a thread-safe Playlist() with:

  • add(song): append one song.
  • add_many(songs): append several as one block, with no other thread's song in the middle.
  • songs() -> list: a copy of the playlist, in order.
  • subscribe(listener): from now on, call listener(song) for every added song (for add_many, per song, in order, after the whole block is in).

Listeners are other people's code: they read the playlist, add songs themselves, or hand work to another thread that calls p.songs() and wait for it.

p = Playlist()
p.subscribe(lambda s: p.add("Encore") if s == "Finale" else None)
p.add("Opener")
p.add_many(["Slow one", "Finale"])
p.songs()   # ["Opener", "Slow one", "Finale", "Encore"]

Nothing may hang, and concurrent adds never lose a song. Two deadlocks wait here: a thread re-taking a plain Lock it holds, and a listener waiting on another thread that needs the lock (an RLock won't save you there). Use one lock per playlist; don't sleep or busy-wait.

Show hint

never call outside code while holding a lock. In add_many, take the lock, extend the list, copy the listeners, release, then call them. add(song) can be add_many([song]).

Topic: Deadlock and lock ordering. The four conditions and how to break one.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc