Concurrency
Overlap the time your program spends waiting, then keep shared data safe when more than one thing touches it. Async and await in your language, threads, locks and pools in Python, and the bugs that only happen sometimes.
- Intermediate
- 4 units, 12 lessons, 152 exercises
- Your language; Python for threads
- Builds on How Computers Work
Unit 01 · 3 lessons
Waiting well
Overlap the time your program spends waiting
- 01Concurrent is not parallel
One cook, two dishes: overlap the waiting
- 02The event loop
One thread, a queue of callbacks, no interruptions
- BOSSThree requests at once
Await together: the slowest, not the sum
Read the unit guide
Most programs spend most of their time waiting: for a server, a disk, a database, a timer. Concurrency means having several tasks in progress at once, so that one task's waiting time is another task's working time. One cook can boil an egg and make toast together, because neither needs hands the whole time.
Concurrent is not parallel. Parallel means two workers running at the same instant, which takes two cores. Work that is mostly waiting is called I/O-bound, and one thread can overlap any number of waits. Work that is mostly computing is CPU-bound, and only more cores make it finish sooner.
An event loop is the simplest concurrency machine: one thread and a queue of callbacks. The loop takes a callback, runs it to the end, and takes the next. Timers and finished I/O add callbacks to the queue. Nothing interrupts a running callback, so a callback that computes or sleeps for two seconds freezes everything else for two seconds.
An async function can pause at await and hand the thread back to the loop until its result is ready. Calling it does not wait: you get a promise (JavaScript) or a coroutine (Python), a ticket for a result. await is what waits for the ticket and unwraps it.
Awaits written one after another add their waits together. To overlap independent waits, start them all, then await them together with gather or Promise.all: the total is the slowest one, not the sum, and the results come back in the order you listed the calls. Work that depends on an earlier result still has to wait for it.
Unit 02 · 3 lessons
Shared state
Find and fix the bugs that only happen sometimes
- 01Race conditions
Read, add, write: three steps that can interleave
- 02Locks
One thread at a time through the critical section
- BOSSThe frozen transfer
Two locks, opposite orders, and the fix
Read the unit guide
Threads share memory, and the operating system may pause one and run another between any two steps. counter += 1 looks like one step but is three: read the value, add one, write it back. If two threads both read before either writes, one update is lost. A result that depends on timing like this is a race condition.
The same bug hides in every check-then-act: test a condition, then act on it, while another thread changes the facts in between. Two buyers both see one seat left, and both take it. Races are rare per run, which is what makes them dangerous: the code passes a thousand tests and fails in production.
A lock (mutex) lets one thread at a time into a critical section: with lock:. Put the whole read-modify-write, or the whole check-and-act, inside one locked block. A lock only works if every thread touching the data takes the same lock, and it protects nothing across the gap between two separate with blocks.
Hold a lock for as short a time as you can. A slow download inside a critical section makes every other thread queue behind it, and the program is sequential again.
Two locks bring a new failure. If one thread holds A and wants B while another holds B and wants A, both wait forever: a deadlock. The standard cure is a global order: everyone takes locks in the same order (lowest account id first), so a cycle of waiting cannot form. Timeouts with a random back-off are the fallback, and they are also how you escape a livelock, where threads keep retrying in step and never get anywhere.
Unit 03 · 3 lessons
Patterns that work
Share less, pass messages, and pick the right kind of worker
- 01Producer and consumer
Hand work between threads through a queue
- 02Worker pools
A fixed crew of workers and a queue of tasks
- BOSSWhy didn't threads make it faster
The GIL, processes, and picking the right tool
Read the unit guide
Locks are easy to get wrong, so the best concurrent designs need few of them. Instead of several threads touching the same data, one thread owns it and the others send it messages. A thread-safe queue is the pipe: producers put items in, consumers get them out, and get waits when the queue is empty. The locking is inside the queue, written once by someone careful.
A consumer needs to be told when the work is over. The usual signal is a sentinel: a special value such as None, put on the queue after the last real item, one per consumer. A bounded queue (maxsize) makes put wait when it is full. That is backpressure: a slow consumer slows the producer down instead of letting the queue eat all the memory.
A pool is that pattern ready-made: a fixed number of workers fed from a queue of tasks. pool.map(f, items) returns results in input order. pool.submit(f, x) returns a future, a ticket for a result. A thread per task does not scale, because each thread costs memory and switching time. Size a pool by the work: many threads for I/O-bound tasks that mostly wait, about one worker per core for CPU-bound tasks.
Standard Python adds a twist. The Global Interpreter Lock (GIL) lets only one thread run Python code at a time, so threads overlap waits but never compute in parallel. CPU-bound Python needs processes, which have their own memory and their own GIL. The price is that everything sent to another process is copied, so tiny tasks cost more to ship than to run.
Picking a tool comes down to one question: is the time spent waiting or computing? Waiting: async or threads. Computing: processes (or worker threads in Node, whose JavaScript also runs on a single thread). A job with both parts gets both tools.
Unit 04 · 3 lessons
Async in the real world
Handle failures, slow replies, stale replies and retries
- 01When a task fails
Errors, timeouts and cancellation in async code
- 02Out of order
Stale replies, and limits on how much runs at once
- BOSSCharged twice
Retries, idempotency and what a timeout really means
Read the unit guide
Real networks fail, stall and answer out of order. An error inside an async call does not crash on the line that started the call: it is stored, and raised where the result is awaited. So the try has to wrap the await. A group of calls awaited together fails fast by default: the first error fails the whole batch, and the other results are dropped. When partial results are worth keeping, ask for every outcome instead (return_exceptions=True in Python, Promise.allSettled in JavaScript).
An await has no time limit of its own, so every wait on something outside your process needs a timeout. When the limit passes, stop waiting and treat it as a failure. Better still, cancel the work, so nothing keeps running for a result nobody will read.
Replies arrive in the order they finish, not the order they were sent. If each reply overwrites the same piece of state, a slow old reply can replace a fast new one. Number the requests and ignore any reply that is not the newest, or cancel the old request when a new one starts. To avoid flooding a service, limit how many requests are in flight at once with a semaphore or a fixed set of workers.
A timeout is ambiguous: the work may not have happened, or it may have happened and only the reply was lost. Retrying is therefore only safe for an idempotent operation, one where doing it twice gives the same result as doing it once. Setting a value is idempotent. Subtracting from a balance is not.
A non-idempotent request is made safe with an idempotency key. The client creates one key per purchase and sends it on every retry. The server remembers the reply for each key and returns it again instead of repeating the work. Retries plus an idempotent handler give the effect of exactly once, which the network alone can never promise.
Learn Concurrency on your phone.
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.