~/problems

Problems

Basics first, then the classics, then company-style assessments. Every problem has tests you run right here; multi-level ones unlock as you go. See the roadmap.

Locks

Lock (mutex)

One thread in a critical section at a time.

Notes

Recognise it when: shared mutable state, "thread-safe", check-then-act (if key not in d: d[key] = ...).

lock = threading.Lock()
with lock:            # acquire/release, even on exceptions
    counter += 1
  • threading.Event for one-shot "X has happened" signals (set() / wait()).
  • RLock only if the same thread must re-acquire. Usually that means the design needs rethinking.

Gotchas

  • Keep critical sections small, and never do I/O or call unknown callbacks while holding a lock.
  • x += 1 is not atomic in Python, GIL or no GIL.

5 problems

Concurrency

Locks Mutexes, lock ordering, readers and writers.

esc