Advanced Python
Multithreading & Async
Complete lesson for Multithreading & Async using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.
Basics — Multithreading & Async
Section: Advanced Python. Overlap waiting work with threads, understand the GIL, synchronise shared state, and use asyncio for concurrent I/O — with deterministic demos.
Concurrency vs parallelism
- Concurrency: structure a program to deal with many tasks at once (interleaving). Parallelism: tasks actually run at the same instant on multiple cores.
- Python threads give concurrency; CPU-heavy parallelism usually needs
multiprocessingbecause of the GIL. - Real life: one barista handling several orders by switching (concurrency) vs two baristas brewing together (parallelism).
| Kind | Tool | Best for |
|---|---|---|
| Threads | threading, ThreadPoolExecutor | I/O-bound waits (network, disk) |
| Processes | multiprocessing, ProcessPoolExecutor | CPU-bound work bypassing the GIL |
| Async IO | asyncio | Many sockets/files with cooperative awaits |
Starting a thread
- Create
threading.Thread(target=fn, args=(...))and callstart(), thenjoin()to wait. - Passing args as a tuple avoids the classic bug of calling the function immediately.
- Name threads for clearer logs:
name="worker-1".
import threading
results = []
def work(label):
results.append(f"{label}-done")
t1 = threading.Thread(target=work, args=("A",), name="t-A")
t2 = threading.Thread(target=work, args=("B",), name="t-B")
t1.start()
t2.start()
t1.join()
t2.join()
print(sorted(results)) Thread life cycle
- Python does not publish a Java-style
Thread.Stateenum, but everythreading.Threadstill moves through clear stages you can observe withis_alive()and how you wait. - **Created (NEW):**
Thread(target=...)exists but has not started —is_alive()isFalse. - **Alive / running:** after
start()the OS schedules the thread; only one thread runs Python bytecode at a time under the GIL, but others can wait on I/O or locks. - **Waiting / blocked:** the thread pauses on
Lock,Condition.wait,Event.wait,join, ortime.sleep(timed wait). - **Terminated:** the target function returns;
is_alive()isFalse. You cannot callstart()again — create a newThread.
| Stage | How you get there | Check / note |
|---|---|---|
| Created | t = Thread(target=fn) | t.is_alive() → False |
| Started / alive | t.start() | t.is_alive() → True |
| Blocked on lock | another thread holds Lock | Waiting to enter with lock: |
| Waiting | Condition.wait(), Event.wait(), join() | Needs notify / set / peer finish |
| Timed waiting | time.sleep(s), wait(timeout) | Returns when time ends or signalled |
| Terminated | target returns (or crashes) | Cannot restart; make a new Thread |
import threading
import time
def work():
time.sleep(0.05)
t = threading.Thread(target=work, name="demo")
print("created:", t.is_alive()) # False
t.start()
print("started:", t.is_alive()) # True
t.join()
print("done:", t.is_alive()) # False
# t.start() # RuntimeError: threads can only be started once Python thread life cycle — created to terminated
A thread is created with Thread(...), becomes alive after
start(), may pause while blocked on a lock or waiting
(Condition/Event/join/sleep, and ends
terminated when the target returns. Think of a chef: hired, cooking, waiting for the stove,
waiting for an order, watching the oven timer, then going home.
- Created → alive: only through
start(), and only once. - Blocked: waiting to acquire a
threading.Lock/RLock. - Waiting / timed:
Condition.wait,Event.wait,join,time.sleep. - Terminated: target finished;
is_alive()isFalse— create a newThreadto run again.
The GIL in plain words
- The Global Interpreter Lock lets only one thread execute Python bytecode at a time in CPython.
- Threads still help when a thread releases the GIL during I/O or in many C extensions (NumPy chunks, etc.).
- For pure-Python CPU loops, prefer processes or vectorised native code — not more threads.
Race conditions and Lock
- A race happens when results depend on timing of shared mutable state updates.
with lock:around the critical section makes check-and-update atomic relative to other threads using the same lock.- Deterministic demos: accumulate under a lock, then print once after
join.
import threading
lock = threading.Lock()
counter = 0
def bump(n):
global counter
for _ in range(n):
with lock:
counter += 1
threads = [threading.Thread(target=bump, args=(1000,)) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print(counter) Queue for thread-safe handoff
queue.Queueis the standard producer/consumer channel — put/get are thread-safe.- Prefer queues over sharing ad-hoc lists without locks.
- Use
task_done/joinwhen workers should drain a batch cleanly.
import queue
import threading
q = queue.Queue()
out = []
def worker():
while True:
item = q.get()
try:
if item is None:
return
out.append(item * item)
finally:
q.task_done()
t = threading.Thread(target=worker)
t.start()
for n in (1, 2, 3, 4):
q.put(n)
q.join()
q.put(None)
t.join()
print(sorted(out)) ThreadPoolExecutor
concurrent.futures.ThreadPoolExecutormanages a pool — submit tasks, collect futures.- For deterministic output, gather
(input, result)pairs and sort before printing. with ThreadPoolExecutor(...) as ex:shuts down the pool cleanly.
from concurrent.futures import ThreadPoolExecutor
def square(n):
return n * n
with ThreadPoolExecutor(max_workers=3) as ex:
futures = {ex.submit(square, n): n for n in range(1, 6)}
pairs = sorted((futures[f], f.result()) for f in futures)
for n, value in pairs:
print(f"{n}^2={value}") asyncio basics
async defdefines a coroutine.awaitpauses until an awaitable finishes without blocking the whole thread.asyncio.run(main())is the usual entry point.asyncio.gatherruns several coroutines concurrently and returns results in the same order as inputs — deterministic.
import asyncio
async def double(n):
await asyncio.sleep(0)
return n * 2
async def main():
values = await asyncio.gather(double(1), double(2), double(3))
print(values)
asyncio.run(main()) Advanced — Multithreading & Async
Deadlocks and lock ordering
- Deadlock: two threads each hold a lock the other needs — forever.
- Prevention: acquire multiple locks in a fixed global order; keep critical sections small; prefer one lock or a queue design.
threading.RLockallows the same thread to acquire again — useful for re-entrant call graphs, not a deadlock cure-all.
import threading
a = threading.Lock()
b = threading.Lock()
log = []
def transfer():
with a:
with b:
log.append("ok")
t1 = threading.Thread(target=transfer)
t2 = threading.Thread(target=transfer)
t1.start()
t2.start()
t1.join()
t2.join()
print(log) Daemon threads and shutdown
- Daemon threads do not keep the process alive; they are killed abruptly at exit — avoid for important writes.
- Prefer explicit
joinwith timeouts and cooperative stop flags/events. threading.Eventis a clean way to signal workers to stop.
import threading
stop = threading.Event()
seen = []
def watcher():
while not stop.is_set():
seen.append("tick")
stop.wait(0.01)
t = threading.Thread(target=watcher)
t.start()
stop.wait(0.05)
stop.set()
t.join()
print(len(seen) > 0) Process pools for CPU work
ProcessPoolExecutorruns callables in child processes — true parallelism for CPU-bound Python.- Arguments and return values must be picklable; avoid huge shared mutable state.
- Process startup is heavier than threads — batch meaningful chunks of work.
from concurrent.futures import ProcessPoolExecutor
def cpu_heavy(n):
return sum(i * i for i in range(n))
if __name__ == "__main__":
with ProcessPoolExecutor(max_workers=2) as ex:
nums = [2000, 3000, 4000]
results = list(ex.map(cpu_heavy, nums))
print(results) asyncio Task coordination
asyncio.create_taskschedules coroutines concurrently on the event loop.- Prefer
gather/TaskGroupfor structured lifetimes; handle exceptions so one failure does not strand siblings. - CPU-bound work inside async code should be offloaded with
asyncio.to_thread(3.9+) or a process pool.
import asyncio
async def labeled(n):
await asyncio.sleep(0)
return f"n={n}"
async def main():
tasks = [asyncio.create_task(labeled(i)) for i in range(3)]
out = [await t for t in tasks]
print(out)
asyncio.run(main()) Choosing the right tool
| Workload | Choose | Why |
|---|---|---|
| Many network calls | asyncio or threads | Waits dominate; overlap them |
| Pure Python CPU loop | processes / native libs | GIL limits thread speedup |
| Simple script + few downloads | ThreadPoolExecutor | Easy API, enough concurrency |
| Shared in-memory state | threads + locks/queues | Processes need IPC |
| Deterministic teaching demos | collect then sort/print | Avoid interleaved races in output |
Tricky Interview Points
Q1) What is the GIL?
Answer The Global Interpreter Lock in CPython allows only one thread to execute Python bytecode at a time. It simplifies memory management but limits CPU-bound thread parallelism.
Q2) When do Python threads help?
Answer For I/O-bound tasks where threads spend time waiting (network, disk). During waits the GIL can be released so other threads run.
Q3) Threads vs processes in Python?
Answer Threads share memory but are limited by the GIL for CPU work. Processes have separate memory and can run CPU-bound Python in parallel, with pickling/IPC costs.
Q4) What is a race condition?
Answer When concurrent updates to shared state make the final result depend on timing, often losing increments without a lock.
Q5) How do you fix shared-counter races?
Answer Protect updates with threading.Lock (or use queue/actors so only one owner mutates state).
Q6) What is ThreadPoolExecutor?
Answer A concurrent.futures executor that reuses a pool of threads to run callables, returning Future objects for results and exceptions.
Q7) What is asyncio?
Answer A library for cooperative concurrent I/O using coroutines, an event loop, and await — single-threaded concurrency without blocking on waits.
Q8) async vs threads?
Answer Async needs awaitable non-blocking APIs and runs on one thread by default. Threads work with blocking libraries but add locking complexity and OS thread costs.
Q9) What is a deadlock?
Answer A state where threads wait forever for locks held by each other. Prevent with consistent lock ordering and smaller critical sections.
Q10) Why is queue.Queue useful?
Answer It provides thread-safe put/get for producer-consumer designs so you avoid hand-rolled locked buffers.
Q11) Are daemon threads safe for writing files?
Answer Risky. Process exit can kill daemon threads mid-write. Use non-daemon workers and join them, or flush in orderly shutdown.
Q12) How do you get deterministic output in concurrent demos?
Answer Avoid printing from many threads without coordination. Collect results, then sort or print on the main thread after joins/gather.
Simple Programs
Deterministic thread pool map
from concurrent.futures import ThreadPoolExecutor
def cube(n):
return n ** 3
with ThreadPoolExecutor(max_workers=4) as ex:
data = list(range(1, 8))
print(list(ex.map(cube, data))) Locked bank account
import threading
class Account:
def __init__(self, balance):
self.balance = balance
self.lock = threading.Lock()
def deposit(self, amount):
with self.lock:
self.balance += amount
def withdraw(self, amount):
with self.lock:
if amount > self.balance:
return False
self.balance -= amount
return True
acct = Account(100)
def customer():
for _ in range(50):
acct.deposit(1)
acct.withdraw(1)
threads = [threading.Thread(target=customer) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print(acct.balance) asyncio gather fan-out
import asyncio
async def fetch(i):
await asyncio.sleep(0)
return {"id": i, "ok": True}
async def main():
results = await asyncio.gather(*(fetch(i) for i in range(5)))
print([r["id"] for r in results])
asyncio.run(main()) Producer-consumer with Queue
import queue
import threading
q = queue.Queue()
consumed = []
def producer():
for n in range(5):
q.put(n)
q.put(None)
def consumer():
while True:
item = q.get()
if item is None:
q.task_done()
break
consumed.append(item)
q.task_done()
p = threading.Thread(target=producer)
c = threading.Thread(target=consumer)
p.start()
c.start()
p.join()
c.join()
print(consumed) asyncio.to_thread offload
import asyncio
import time
def blocking_sum(n):
return sum(range(n))
async def main():
result = await asyncio.to_thread(blocking_sum, 10000)
print(result)
asyncio.run(main()) Problem Solving Tricks
- Never print unordered thread logs in tutorials — collect, sort, then print for stable output.
ex.mappreserves input order in results;as_completeddoes not.- Protect every read-modify-write on shared mutables with the same lock.
- Prefer
queue.Queueover locked lists for producer/consumer. - Use
if __name__ == "__main__":guards withProcessPoolExecutoron Windows. asyncio.gather(*tasks)returns results in the same order as the input awaitables.- Set
stopEvents instead of killing threads. - CPU-bound? Measure before adding threads — the GIL may make them slower.
join()without a priorstart()pattern check is a common hang cause — always start all, then join all.- Keep locks ordered (
athenbeverywhere) to avoid deadlocks.
Practice Programs List
- Bump a shared counter with and without a lock; explain the wrong totals.
- Download-shaped demo: simulate I/O with
time.sleepin a thread pool and collect timings on the main thread. - Rewrite a thread pool example using
asyncio.gatherandasyncio.sleep(0). - Build a worker pool that stops via
threading.Event. - Create a deadlock on purpose with two locks, then fix lock order.
- Use
ProcessPoolExecutorto compute prime counts for several ranges and print a sorted table. - Implement producer/consumer where the consumer sorts batches before appending to a result list.
- Offload a blocking function from async code with
asyncio.to_thread.