Solly
Lesson

03 Concurrency and shared state

Concurrency and shared state

First: what happens when two calls overlap?

A thread is one path of program execution. Two threads may access the same object at nearly the same time, and their steps can interleave. Even if each instruction looks simple, count = count + 1 reads an old value and writes a new one: two callers can accidentally lose an update.

A lock lets only one thread hold a protected section at a time. The program must protect the whole read-check-update sequence, not just the last assignment. A condition combines a lock with a way to wait for a situation to become true and notify waiting threads when that situation changes. A waiting thread releases the condition lock while it waits, then re-checks its rule after waking.

Reason through the first queue in words before coding:

  1. Capacity is one; producer A puts first. The queue is now full.
  2. Producer B calls put('second'): it must wait, not overwrite or reject the item.
  3. Consumer takes first; it notifies waiting producers after freeing the slot.
  4. Producer B wakes, checks that space really exists, and completes.
  5. The next take returns second. A wait belongs inside a while check, because waking does not guarantee the state is still safe.

Why with, @contextmanager and yield appear: a context manager runs entry code, temporarily gives control to the body, and runs cleanup even when the body fails:

from contextlib import contextmanager

@contextmanager
def session():
    print("enter")
    try:
        yield
    finally:
        print("leave")

with session():
    print("work")
# enter, work, leave

Reader/writer timeline: reader A already holds the read lock. Writer B arrives and must wait for A to leave. Reader C arrives after B is waiting: to prevent writer starvation, C also waits instead of passing B. When A exits, B writes alone; only after B releases may C enter. Distinguish two readers overlapping from a writer remaining exclusive and not being repeatedly skipped. The visible tests must check every promise in the requirement.

Striping and rate limits: a striped map chooses a stable lock for each key. Two calls touching the same key protect their entire read/modify/write; different keys may land on different locks. In a token bucket with capacity 2, refill 1 token/second and a fixed clock: two calls succeed, the third fails, and moving the clock one second permits one more call. Protect that decision under the same lock so concurrent callers cannot spend one token twice.

The four challenges grow from bounded queues to reader/writer coordination, striped counters and token-bucket limits. They require basic Python threading and with context-manager knowledge. If these are new, read the short example above, inspect the visible stress test and trace the order of two callers before building classes. Do not infer correctness from a test passing on one lucky scheduling run.


Concurrency makes Ownership and Topology concrete: which state and synchronization primitive are shared, which scope owns them, and how calls block or overlap at runtime. These exercises test blocking, exclusivity, atomicity, and shared-state lifetime. The validator repeats concurrency stresses to reduce dependence on lucky scheduling.

Sign in with an enabled provider to save your lesson progress.
Sign in to track progress

Loading sign-in options…