Lesson · Concurrency Fundamentals
Threading
81 min readThreading
Threads share memory and run within one process. They are effective for many I/O workloads, but shared state introduces races and requires synchronization regardless of whether the runtime has a GIL.
Learning goals
- Start threads with
threading.Threadand join them, and say whatjoin()guarantees about ordering. - Explain why two threads incrementing a shared counter can lose updates even when the increment is a single source line.
- Use a
Lockas a context manager to make a read-modify-write sequence atomic. - Recognize when a primitive other than a lock fits better:
Event,ConditionorSemaphore. - State why a runtime lock such as the GIL does not make shared mutable state safe, and what still needs protecting.
Mental model
Threads are execution streams inside one process, so they see the same counter object and the same lock; the only question is which sequences of their steps can interleave. The worked example makes every interleaving harmless by wrapping the read-modify-write in one critical section.
Mental model
read it top to bottom
Thread(target=increment, args=(10_000,)) four threads, one process, one counter ↓ start() each thread runs the loop concurrently counter += 1 interleaved read, add and store can interleave ↓ with lock: one holder at a time, increments land join() in the main thread the final counter can be read safely
Core idea
Threaded programs are written against a schedule you cannot see: the same source can run in any interleaving, so correctness has to hold for all of them rather than for the one that happened in a demo. The primitives in this lesson each answer a different coordination need: a Lock makes a critical section atomic, an Event signals that something happened, a Condition waits for a state to become true, and a Semaphore bounds how many threads use a resource at once. Choosing among them is a question about what must be communicated, not about which primitive looks neatest.
threading.Thread
In Threading, threading.Thread names a concrete behavior, API choice, or runtime rule that you should be able to recognize in code. Trace one example from input to result, record any mutation or allocation that occurs, and note the exception or fallback behavior for an invalid case. Then compare that behavior with the nearest alternative from this lesson instead of memorizing the term in isolation.
Starting/joining
In Threading, Starting/joining names a concrete behavior, API choice, or runtime rule that you should be able to recognize in code. Trace one example from input to result, record any mutation or allocation that occurs, and note the exception or fallback behavior for an invalid case. Then compare that behavior with the nearest alternative from this lesson instead of memorizing the term in isolation.
Shared memory
Shared memory lets concurrent workers observe the same mutable state without serialization. Every invariant spanning that state needs an appropriate synchronization strategy.
Race conditions
A race condition occurs when correctness depends on the relative timing of concurrent operations. Protect invariants rather than assuming a particular thread or task schedule.
Locks
A Lock from threading is a mutual-exclusion flag: exactly one thread holds it at a time, and every other acquire() blocks until release() runs. The worked example wraps counter += 1 in with lock: so the read-modify-write cannot interleave, and the context manager releases the lock even when the body raises.
RLock
RLock is a reentrant lock that the owning thread can acquire multiple times. In Threading, pay attention to its return value, side effects, and exceptions rather than memorizing only the call syntax.
Events
An Event is a one-bit signal shared between threads: set() marks it done and wakes every waiter, clear() unsets it, and wait() blocks until the bit is set. Use it for start and stop coordination rather than for protecting compound state, because it carries no data and grants no ownership.
Conditions
A Condition combines a lock with waiting: inside with cond:, cond.wait() releases the lock and sleeps until another thread calls notify() or notify_all(), then reacquires the lock before returning. This fits threads that must wait for a predicate, such as a buffer becoming non-empty.
Semaphores
A Semaphore is a counter with a blocking acquire: acquire() waits until the count is positive and then decrements it, and release() increments it. An initial count of n admits at most n threads at once, which caps concurrent access to a limited resource.
Walkthrough
counter = 0is a module-level name andlock = Lock()guards it;incrementdeclaresglobal counterand runscounter += 1insidewith lock:, which is the read-modify-write the lock exists to protect.- Four
Threadobjects each runincrement(10_000)on the same function object, so all four mutate one shared name; without thewith lock:line, the read, add and store of two threads can interleave and lose increments. start()launches each thread, and the second loop'sjoin()waits for each to finish beforeprint(counter)runs, so the total is read only after every increment has landed.- Predict before running: the printed total with the lock in place, what the total becomes when the
with lock:wrapper is removed, and why the unlocked run can print a different number each time.
Experiments to try
- Remove the
with lock:wrapper (keep the body's indentation) and run the program several times; collect the different totals and explain the variance. - Raise the worker count from four to eight and the per-worker loop from
10_000to100_000; check whether the locked version still prints the exact total. - Replace the lock with a
Semaphore(1)and confirm the behavior matches, then decide which of the two communicates the intent better. - Time the locked and unlocked versions and measure what the synchronization costs instead of guessing.
Common mistakes
- Incrementing shared state without a critical section:
counter += 1is a read, an add and a store, so two threads can both read the old value and one update silently vanishes. - Using
sleepto hope orderings resolve: timing changes the window in which a race occurs but establishes no invariant, so the bug simply resurfaces at different speeds. - Holding a lock while doing slow work: a lock held across I/O serializes every other thread behind one long operation, which converts a synchronization fix into a throughput problem.
- Forgetting to join before reading results: the main thread then observes a partially finished run and reports a count that is not final.
Practice: Easy
- Run the worked example and confirm the total; then remove the lock and run it five times, recording each total.
- Change the per-worker count to
1_000_000in the unlocked version and note whether the missing increments grow or shrink relative to the total. - Add a
print(thread.name, counter)line inside the locked section and describe how the four threads take turns.
Practice: Medium
- Rewrite
incrementto update a counter stored inside adict(still under a lock) and verify the same exact total. - Build a stop signal with
threading.Event: workers loop untilstop.is_set(), the main thread sets it after a short run, and every worker exits; compare that shape with running forever and leaning onjoin(timeout). - Use a
Semaphore(2)to admit at most two threads into a slow section, and record the timing difference against a version with no limiter.
Practice: Hard
- Design the synchronization plan for a small worker pool: name the shared invariant, the critical sections, the primitive for each signal, and where each thread starts and stops.
- Build a failure lab: a lost update from an unlocked increment, a
join()that never returns because a worker blocks on a lock nobody releases, and a lock held acrosssleepwhile other threads starve; explain each mechanism. - Take the worked example and make shutdown cooperative with an
Eventinstead of a fixed loop count; prove with a bounded script that no thread outlives the main one.
Lesson checklist
- I can start threads and join them, and say what
join()guarantees about ordering. - I can explain why one source line is not one atomic step.
- I can wrap a read-modify-write sequence in a
Lockand show the total is stable. - I can pick between
Lock,Event,ConditionandSemaphorefor a coordination need.
Remember
Threads share one process, so shared state stays cheap to read and easy to corrupt: any compound operation such as `counter += 1` can interleave, and the schedule that hides the bug is not the schedule you will get. The synchronization primitives each answer a different question (atomicity, signalling, waiting for a condition, bounding concurrency), and naming the question first is what makes the choice obvious.
Interview angles
What is the main purpose of **threading.Thread**?+
In Threading, threading.Thread names a concrete behavior, API choice, or runtime rule that you should be able to recognize in code. Trace one example from input to result, record any mutation or allocation that occurs, and note the exception or fallback behavior for an invalid case. Then compare that behavior with the nearest alternative from this lesson instead of memorizing the term in isolation.
What should you pay attention to when using **Starting/joining**?+
In Threading, Starting/joining names a concrete behavior, API choice, or runtime rule that you should be able to recognize in code. Trace one example from input to result, record any mutation or allocation that occurs, and note the exception or fallback behavior for an invalid case. Then compare that behavior with the nearest alternative from this lesson instead of memorizing the term in isolation.
How does **Shared memory** fit into this lesson?+
Shared memory lets concurrent workers observe the same mutable state without serialization. Every invariant spanning that state needs an appropriate synchronization strategy.
Why can two threads running `counter += 1` lose an increment even though it is a single line?+
The line is a read, an add and a store; two threads can both read the same old value before either stores, so one update overwrites the other. A lock around the whole sequence makes it atomic.