Part 13 / Stage 3
Concurrency
Goal: Make programs that wait on the network or disk finish much faster with threads or
asyncio, speed up heavy maths with processes, and keep shared data safe. Time: ~1 hour
What you will learn
- Concurrency vs parallelism, and I/O-bound vs CPU-bound work
- Threads:
threading.Thread,start()/join(), arguments, daemon threads - Race conditions,
threading.Lock, andqueue.Queuefor producer–consumer - The GIL: why threads don't speed up CPU work, and the new free-threaded build
multiprocessing:Process,Pool.map, and whyif __name__ == "__main__":mattersconcurrent.futures: thread and process pools withsubmit,map,as_completedasyncio:async def,await,asyncio.run,gather,TaskGroup,timeout, cancelling- Async I/O in practice:
asyncio.to_thread,asyncio.Queue,Semaphore - Common pitfalls, and a parallel downloader done three ways
Everything runs offline. Waiting is faked with
time.sleep/asyncio.sleep, or with a tiny local web server,examples/file_server.py, that runs on your own computer in a background thread. Run the snippets that sayfrom file_server import ...from inside theexamples/folder.Timings vary. Lines marked
(time varies)depend on your computer. Your numbers will be a little different; the pattern (which one is faster) is what matters.
Topics in this part
Practice
Python workbench — write and run code here
Press Run and Python 3.14 loads right in your browser (a one-time download of about 15 MB; after that it works offline). Your code never leaves this page. input() opens a small prompt window.
Use only the standard library. Every exercise runs offline: waiting is faked with time.sleep / asyncio.sleep, or with a local http.server. Timings change from computer to computer, so the sample outputs check results and order, not seconds.
Exercise 1: Parallel greeting cards
Scenario: A shop writes Diwali cards for its guests. Each card takes 0.2 s, and you want them all written at once. What to do:
- Write
write_card(index, name, cards)that sleeps 0.2 s, then storesHappy Diwali, <name>!incards[index]. - Write
make_cards(guests)that makes a list[""] * len(guests), starts onethreading.Threadper guest (pass the arguments withargs=), joins them all and returns the list. - Time
make_cards(GUESTS)withtime.perf_counter(). Print each card, the number of cards, and whether it took less than0.2 * len(GUESTS)seconds.
Starting data:
GUESTS = ["Asha", "Vikram", "Fatima", "Joseph"]
Sample output:
Happy Diwali, Asha!
Happy Diwali, Vikram!
Happy Diwali, Fatima!
Happy Diwali, Joseph!
Cards: 4
Faster than one by one: True
💡 Hint: Each thread writes its own slot (cards[index]), so the order stays the same as GUESTS no matter which thread finishes first. enumerate(guests) gives you the index.
Show the solution to Exercise 1
"""Exercise 1: Parallel greeting cards (Thread, args, start/join).
Run: python ex01.py (macOS/Linux: python3 ex01.py)
"""
import threading
import time
GUESTS = ["Asha", "Vikram", "Fatima", "Joseph"]
def write_card(index: int, name: str, cards: list[str]) -> None:
time.sleep(0.2) # writing a card takes a while
cards[index] = f"Happy Diwali, {name}!"
def make_cards(guests: list[str]) -> list[str]:
cards = [""] * len(guests)
threads = [
threading.Thread(target=write_card, args=(i, name, cards))
for i, name in enumerate(guests)
]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
return cards
def main() -> None:
start = time.perf_counter()
cards = make_cards(GUESTS)
seconds = time.perf_counter() - start
for card in cards:
print(card)
print("Cards:", len(cards))
print("Faster than one by one:", seconds < 0.2 * len(GUESTS))
if __name__ == "__main__":
main()
Exercise 2: Ticket counter
Scenario: A cinema has 4 ticket counters selling at the same time. The total must be exact. What to do:
- Write a class
TicketCounterwith asoldattribute (starts at0), athreading.Lock, and a methodsell()that adds 1 tosoldinsidewith self._lock:. - Write
sell_many(counter, how_many)that callscounter.sell()how_manytimes. - Start
COUNTERSthreads that each runsell_many(counter, TICKETS_EACH), join them, and print the total and whether it equalsCOUNTERS * TICKETS_EACH.
Starting data:
COUNTERS = 4
TICKETS_EACH = 25_000
Sample output:
Tickets sold: 100,000
Correct: True
💡 Hint: self.sold += 1 is a read and then a write, so two threads can overwrite each other. The lock makes it safe. f"{n:,}" adds the commas.
Show the solution to Exercise 2
"""Exercise 2: Ticket counter (race condition fixed with a Lock).
Run: python ex02.py (macOS/Linux: python3 ex02.py)
"""
import threading
COUNTERS = 4
TICKETS_EACH = 25_000
class TicketCounter:
def __init__(self) -> None:
self.sold = 0
self._lock = threading.Lock()
def sell(self) -> None:
with self._lock:
self.sold += 1
def sell_many(counter: TicketCounter, how_many: int) -> None:
for _ in range(how_many):
counter.sell()
def main() -> None:
counter = TicketCounter()
threads = [
threading.Thread(target=sell_many, args=(counter, TICKETS_EACH))
for _ in range(COUNTERS)
]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
expected = COUNTERS * TICKETS_EACH
print(f"Tickets sold: {counter.sold:,}")
print("Correct:", counter.sold == expected)
if __name__ == "__main__":
main()
Exercise 3: Pick the right tool
Scenario: Your team lead gives you a list of jobs and asks which concurrency tool fits each one. What to do:
- Write
pick_tool(kind, async_code)that returns"ProcessPoolExecutor"for"cpu"work,"asyncio"for"io"work whenasync_codeisTrue, and"ThreadPoolExecutor"for other"io"work. - For every task in
TASKS, print the name (width 30), the kind (width 4),->and the tool.
Starting data:
TASKS = [
("Download 200 product images", "io", False),
("Resize 500 photos", "cpu", False),
("Call 50 courier APIs", "io", True),
("Count words in 10 GB of logs", "cpu", False),
("Read one small config file", "io", False),
]
Sample output:
Download 200 product images io -> ThreadPoolExecutor
Resize 500 photos cpu -> ProcessPoolExecutor
Call 50 courier APIs io -> asyncio
Count words in 10 GB of logs cpu -> ProcessPoolExecutor
Read one small config file io -> ThreadPoolExecutor
💡 Hint: Unpack each tuple in the for line: for name, kind, async_code in TASKS:. Use f"{name:<30} {kind:<4} -> ...". (In real life, one small file needs no concurrency at all: see the decision table in section 6.)
Show the solution to Exercise 3
"""Exercise 3: Pick the right tool (I/O-bound vs CPU-bound).
Run: python ex03.py (macOS/Linux: python3 ex03.py)
"""
TASKS = [
("Download 200 product images", "io", False),
("Resize 500 photos", "cpu", False),
("Call 50 courier APIs", "io", True),
("Count words in 10 GB of logs", "cpu", False),
("Read one small config file", "io", False),
]
def pick_tool(kind: str, async_code: bool) -> str:
if kind == "cpu":
return "ProcessPoolExecutor"
if async_code:
return "asyncio"
return "ThreadPoolExecutor"
def main() -> None:
for name, kind, async_code in TASKS:
print(f"{name:<30} {kind:<4} -> {pick_tool(kind, async_code)}")
if __name__ == "__main__":
main()
Exercise 4: Parcel sorting line
Scenario: At a courier hub, parcels arrive on a belt and 3 sorters put each one into a city bin. What to do:
- Write
sorter(parcels, bins, lock): in a loop,get()an item from thequeue.Queue; stop when it isSTOP(None); otherwise sleep 0.05 s and append the parcel id tobins[city](a dict of lists), while holdinglock. - Write
sort_parcels(items)that startsSORTERSthreads, puts every parcel on the queue, then oneSTOPper sorter, joins the threads and returnsbins. - Print each city in alphabetical order with its sorted list of ids, then the total number of parcels.
Starting data:
PARCELS = [
("P101", "Pune"), ("P102", "Delhi"), ("P103", "Pune"),
("P104", "Chennai"), ("P105", "Delhi"), ("P106", "Pune"),
]
STOP = None
SORTERS = 3
Sample output:
Chennai ['P104']
Delhi ['P102', 'P105']
Pune ['P101', 'P103', 'P106']
Total parcels: 6
💡 Hint: Which sorter handles which parcel changes every run, so sort before printing. bins.setdefault(city, []).append(parcel_id) creates the list the first time. The queue needs no lock, but the shared dict does.
Show the solution to Exercise 4
"""Exercise 4: Parcel sorting line (queue.Queue producer-consumer).
Run: python ex04.py (macOS/Linux: python3 ex04.py)
"""
import queue
import threading
import time
PARCELS = [
("P101", "Pune"), ("P102", "Delhi"), ("P103", "Pune"),
("P104", "Chennai"), ("P105", "Delhi"), ("P106", "Pune"),
]
STOP = None
SORTERS = 3
def sorter(
parcels: queue.Queue, bins: dict[str, list[str]], lock: threading.Lock
) -> None:
while True:
item = parcels.get()
if item is STOP:
break
parcel_id, city = item
time.sleep(0.05) # scanning the label
with lock: # several sorters share the dict
bins.setdefault(city, []).append(parcel_id)
def sort_parcels(items: list[tuple[str, str]]) -> dict[str, list[str]]:
parcels: queue.Queue = queue.Queue()
bins: dict[str, list[str]] = {}
lock = threading.Lock()
workers = [
threading.Thread(target=sorter, args=(parcels, bins, lock))
for _ in range(SORTERS)
]
for worker in workers:
worker.start()
for item in items:
parcels.put(item)
for _ in workers:
parcels.put(STOP)
for worker in workers:
worker.join()
return bins
def main() -> None:
bins = sort_parcels(PARCELS)
for city in sorted(bins):
print(f"{city:<8} {sorted(bins[city])}")
print("Total parcels:", sum(len(ids) for ids in bins.values()))
if __name__ == "__main__":
main()
Exercise 5: GST for invoice batches
Scenario: Each branch of a shop sends a batch of invoice amounts. Totalling big batches is CPU work, so you spread it over processes. What to do:
- Write
batch_total_with_gst(amounts)that returns the sum plus 18% GST in whole rupees:subtotal + subtotal * GST_RATE // 100. - In
main(), useProcessPoolExecutor(max_workers=2)andpool.mapoverBATCHES.values(). - Print each city with its total, then the grand total. Remember the
__main__guard.
Starting data:
BATCHES = {
"Mumbai": [1200, 450, 3000, 799],
"Kolkata": [250, 250, 999],
"Jaipur": [15000, 2200],
"Kochi": [80, 120, 60, 40, 300],
}
GST_RATE = 18
Sample output:
Mumbai ₹6,429
Kolkata ₹1,768
Jaipur ₹20,296
Kochi ₹708
All ₹29,201
💡 Hint: pool.map returns results in the same order as the input, so zip(BATCHES, totals) pairs each city with its total. The function must be at the top level of the file so the worker processes can import it.
Show the solution to Exercise 5
"""Exercise 5: GST for big invoice batches (ProcessPoolExecutor.map).
Run: python ex05.py (macOS/Linux: python3 ex05.py)
"""
from concurrent.futures import ProcessPoolExecutor
BATCHES = {
"Mumbai": [1200, 450, 3000, 799],
"Kolkata": [250, 250, 999],
"Jaipur": [15000, 2200],
"Kochi": [80, 120, 60, 40, 300],
}
GST_RATE = 18
def batch_total_with_gst(amounts: list[int]) -> int:
"""Total of the batch plus 18% GST, in whole rupees."""
subtotal = sum(amounts)
return subtotal + subtotal * GST_RATE // 100
def main() -> None:
cities = list(BATCHES)
with ProcessPoolExecutor(max_workers=2) as pool:
totals = list(pool.map(batch_total_with_gst, BATCHES.values()))
for city, total in zip(cities, totals):
print(f"{city:<8} ₹{total:,}")
print(f"All ₹{sum(totals):,}")
if __name__ == "__main__":
main()
Exercise 6: Morning tea orders
Scenario: Three tables order tea at once. You want to serve the slips in order but also know which tea was ready first. What to do:
- Write
async def brew(table, drink, seconds, finished)that doesawait asyncio.sleep(seconds), appendstableto thefinishedlist, and returns"<table>: <drink>". - In
async def main(), run all orders with oneasyncio.gather. - Print the gathered results (indented by 2 spaces), then the finish order joined with
,. Start it withasyncio.run(main()).
Starting data:
ORDERS = [
("Table 1", "masala chai", 0.3),
("Table 2", "green tea", 0.1),
("Table 3", "ginger chai", 0.2),
]
Sample output:
Served (gather order):
Table 1: masala chai
Table 2: green tea
Table 3: ginger chai
Finished first to last: Table 2, Table 3, Table 1
💡 Hint: await asyncio.gather(*(brew(t, d, s, finished) for t, d, s in ORDERS)). The * spreads the coroutines as separate arguments. gather keeps the input order; the finished list shows the real finish order.
Show the solution to Exercise 6
"""Exercise 6: Morning tea orders (asyncio.gather and finish order).
Run: python ex06.py (macOS/Linux: python3 ex06.py)
"""
import asyncio
ORDERS = [
("Table 1", "masala chai", 0.3),
("Table 2", "green tea", 0.1),
("Table 3", "ginger chai", 0.2),
]
async def brew(table: str, drink: str, seconds: float, finished: list[str]) -> str:
await asyncio.sleep(seconds)
finished.append(table)
return f"{table}: {drink}"
async def main() -> None:
finished: list[str] = []
served = await asyncio.gather(
*(brew(table, drink, s, finished) for table, drink, s in ORDERS)
)
print("Served (gather order):")
for line in served:
print(" ", line)
print("Finished first to last:", ", ".join(finished))
if __name__ == "__main__":
asyncio.run(main())
Exercise 7: Fastest delivery quote
Scenario: A food app asks four delivery partners for a price. Slow partners must not hold up the customer. What to do:
- Write
async def get_quote(partner)that sleepsPARTNERS[partner]seconds and returnsPRICES[partner]. - Write
async def quote_or_none(partner)that callsget_quoteinsideasync with asyncio.timeout(TIME_LIMIT):and returnsNoneonTimeoutError. - In
main(), start one task per partner in anasyncio.TaskGroup. After the block, print each partner with₹<price>ortimed out(name width 10), then the cheapest partner that answered.
Starting data:
PARTNERS = {"SwiftRide": 0.1, "QuickBox": 0.6, "CityDash": 0.2, "SlowCart": 0.9}
PRICES = {"SwiftRide": 60, "QuickBox": 35, "CityDash": 45, "SlowCart": 25}
TIME_LIMIT = 0.4
Sample output:
SwiftRide ₹60
QuickBox timed out
CityDash ₹45
SlowCart timed out
Best quote: CityDash at ₹45
💡 Hint: A dict comprehension {name: group.create_task(...) for name in PARTNERS} keeps each task with its name. After the async with block every task is done, so task.result() is ready. min(quotes, key=quotes.get) gives the key with the smallest value. The whole program takes about 0.4 s, not 0.9 s.
Show the solution to Exercise 7
"""Exercise 7: Fastest delivery quote (TaskGroup + asyncio.timeout).
Run: python ex07.py (macOS/Linux: python3 ex07.py)
"""
import asyncio
PARTNERS = {"SwiftRide": 0.1, "QuickBox": 0.6, "CityDash": 0.2, "SlowCart": 0.9}
PRICES = {"SwiftRide": 60, "QuickBox": 35, "CityDash": 45, "SlowCart": 25}
TIME_LIMIT = 0.4
async def get_quote(partner: str) -> int:
await asyncio.sleep(PARTNERS[partner]) # the partner's API is slow
return PRICES[partner]
async def quote_or_none(partner: str) -> int | None:
try:
async with asyncio.timeout(TIME_LIMIT):
return await get_quote(partner)
except TimeoutError:
return None
async def main() -> None:
async with asyncio.TaskGroup() as group:
tasks = {name: group.create_task(quote_or_none(name)) for name in PARTNERS}
quotes = {}
for name, task in tasks.items():
price = task.result()
if price is None:
print(f"{name:<10} timed out")
else:
print(f"{name:<10} ₹{price}")
quotes[name] = price
best = min(quotes, key=quotes.get)
print(f"Best quote: {best} at ₹{quotes[best]}")
if __name__ == "__main__":
asyncio.run(main())
Exercise 8: Polite page checker
Scenario: Before a website launch, you check every page for broken links, but you must never send more than 2 requests at once. What to do:
- Start a local
ThreadingHTTPServeron127.0.0.1, port0, in a daemon thread. Its handler sleeps 0.2 s, answers404for paths inMISSINGand200for the rest, and records the highest number of requests it was serving at the same time (server.max_at_once, protected by a lock). - Write a blocking
get_status(url)withurllib.request.urlopen(url, timeout=5)that returns the status code (for a 404, catchurllib.error.HTTPErrorand returnerror.code). - Write
async def check_page(base_url, path, limit)that callsget_statuswithasyncio.to_threadinsideasync with limit:and returns"<path:<10> <status> OK"or... BROKEN. - Check all
PAGESwithasyncio.gatherandasyncio.Semaphore(MAX_AT_ONCE). Stop the server, then print each line, the number of broken pages, andserver.max_at_once.
Starting data:
PAGES = ["/home", "/menu", "/offers", "/old-page", "/contact", "/careers"]
MISSING = {"/old-page", "/careers"}
MAX_AT_ONCE = 2
Sample output:
/home 200 OK
/menu 200 OK
/offers 200 OK
/old-page 404 BROKEN
/contact 200 OK
/careers 404 BROKEN
Broken pages: 2
Most requests at once: 2
💡 Hint: Look at examples/file_server.py for the server and the "requests at once" counter. Call asyncio.run(check_all(base_url)) inside try and stop the server in finally. sum(line.endswith("BROKEN") for line in lines) counts True as 1.
Show the solution to Exercise 8
"""Exercise 8: Polite page checker (to_thread + Semaphore + local server).
Starts its own tiny http.server in a background thread (no internet).
Run: python ex08.py (macOS/Linux: python3 ex08.py)
"""
import asyncio
import threading
import time
import urllib.error
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
PAGES = ["/home", "/menu", "/offers", "/old-page", "/contact", "/careers"]
MISSING = {"/old-page", "/careers"}
MAX_AT_ONCE = 2
class PageHandler(BaseHTTPRequestHandler):
def do_GET(self) -> None:
server = self.server
with server.lock:
server.active += 1
server.max_at_once = max(server.max_at_once, server.active)
time.sleep(0.2)
status = 404 if self.path in MISSING else 200
self.send_response(status)
self.send_header("Content-Length", "0")
self.end_headers()
with server.lock:
server.active -= 1
def log_message(self, *args) -> None:
"""Stay quiet."""
def start_server() -> tuple[ThreadingHTTPServer, str]:
server = ThreadingHTTPServer(("127.0.0.1", 0), PageHandler)
server.lock = threading.Lock()
server.active = 0
server.max_at_once = 0
threading.Thread(target=server.serve_forever, daemon=True).start()
return server, f"http://127.0.0.1:{server.server_port}"
def get_status(url: str) -> int:
"""Blocking call: return the HTTP status code of url."""
try:
with urllib.request.urlopen(url, timeout=5) as response:
return response.status
except urllib.error.HTTPError as error:
return error.code
async def check_page(base_url: str, path: str, limit: asyncio.Semaphore) -> str:
async with limit:
status = await asyncio.to_thread(get_status, base_url + path)
return f"{path:<10} {status} {'OK' if status == 200 else 'BROKEN'}"
async def check_all(base_url: str) -> list[str]:
limit = asyncio.Semaphore(MAX_AT_ONCE)
return await asyncio.gather(*(check_page(base_url, p, limit) for p in PAGES))
def main() -> None:
server, base_url = start_server()
try:
lines = asyncio.run(check_all(base_url))
finally:
server.shutdown()
server.server_close()
for line in lines:
print(line)
print("Broken pages:", sum(line.endswith("BROKEN") for line in lines))
print("Most requests at once:", server.max_at_once)
if __name__ == "__main__":
main()
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Thread(target=work()) |
Calls work right now, in the main thread, and passes its result |
Thread(target=work), no () |
args=("chai") |
That is a string, not a tuple | args=("chai",) with a comma |
Forgetting .join() |
You read results before the threads have finished | join() every thread, or use a pool with with |
| Changing shared data from many threads without a lock | Lost updates: wrong totals that appear only sometimes | with lock: or a queue.Queue |
| Threads for heavy maths on normal Python | The GIL lets only one run at a time: no speed-up | ProcessPoolExecutor or multiprocessing.Pool |
No if __name__ == "__main__": with processes |
On Windows/macOS each child re-runs your file and starts more children | Always put the start code under the guard |
time.sleep() or urllib directly inside async def |
Freezes the whole event loop | await asyncio.sleep() / await asyncio.to_thread(...) |
Calling a coroutine without await |
It never runs; you get a coroutine object | await coro(), or asyncio.create_task(coro()) |
Swallowing CancelledError |
The task can't be cancelled properly | Clean up, then raise |
| Starting thousands of requests at once | Overloads the server, may get you blocked | Semaphore(N) or max_workers=N |
Quick recap
- Concurrency = switching between waiting tasks; parallelism = many cores at once.
- I/O-bound → threads or
asyncio; CPU-bound → processes. Thread(target=f, args=(...)),.start(),.join(); daemon threads stop with the program.- Shared data + threads = race conditions; protect it with
with lock:or pass work throughqueue.Queue. - The GIL lets one thread run Python at a time on the normal build; free-threaded Python (3.13t experimental, 3.14 supported, not default) removes it.
multiprocessingandProcessPoolExecutoruse many cores; always use the__main__guard.concurrent.futures:submit→ Future,mapkeeps input order,as_completedgives finish order.asyncio:async def+await, start withasyncio.run, run many withgather/TaskGroup, limit withtimeoutandSemaphore, wrap blocking calls withto_thread.
Checklist
- I can tell whether a task is I/O-bound or CPU-bound and pick a tool for it.
- I can start threads with arguments and wait for them with
join(). - I can show a race condition and fix it with a
Lock, or use aqueue.Queue. - I can explain the GIL and check for it with
sys._is_gil_enabled(). - I can use
Pool.map/ProcessPoolExecutorwith the__main__guard. - I can use
submit,mapandas_completedwith a thread pool. - I can write
asynccode withgather,TaskGroup,timeoutand cancellation. - I can call blocking code with
asyncio.to_threadand limit concurrency with aSemaphore.