Skip to main content

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.

L1

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 multiprocessing because of the GIL.
  • Real life: one barista handling several orders by switching (concurrency) vs two baristas brewing together (parallelism).
KindToolBest for
Threadsthreading, ThreadPoolExecutorI/O-bound waits (network, disk)
Processesmultiprocessing, ProcessPoolExecutorCPU-bound work bypassing the GIL
Async IOasyncioMany sockets/files with cooperative awaits

Starting a thread

  • Create threading.Thread(target=fn, args=(...)) and call start(), then join() 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.State enum, but every threading.Thread still moves through clear stages you can observe with is_alive() and how you wait.
  • **Created (NEW):** Thread(target=...) exists but has not started — is_alive() is False.
  • **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, or time.sleep (timed wait).
  • **Terminated:** the target function returns; is_alive() is False. You cannot call start() again — create a new Thread.
StageHow you get thereCheck / note
Createdt = Thread(target=fn)t.is_alive() → False
Started / alivet.start()t.is_alive() → True
Blocked on lockanother thread holds LockWaiting to enter with lock:
WaitingCondition.wait(), Event.wait(), join()Needs notify / set / peer finish
Timed waitingtime.sleep(s), wait(timeout)Returns when time ends or signalled
Terminatedtarget 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.

Python thread life cycle diagram: NEW/CREATED goes to RUNNING/ALIVE with start(). RUNNING goes to BLOCKED waiting for a Lock and back when it gets the lock; to WAITING with wait join or Event and back with notify set or peer done; to TIMED WAITING with sleep or wait timeout and back when time is over; and to TERMINATED when the target finishes. A side card compares each state to a chef in a kitchen.
Python thread life cycle — numbered arrows show each transition; the chef card gives a real-life meaning for every stage
  • 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() is False — create a new Thread to 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.Queue is the standard producer/consumer channel — put/get are thread-safe.
  • Prefer queues over sharing ad-hoc lists without locks.
  • Use task_done / join when 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.ThreadPoolExecutor manages 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 def defines a coroutine. await pauses until an awaitable finishes without blocking the whole thread.
  • asyncio.run(main()) is the usual entry point.
  • asyncio.gather runs 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())
L2

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.RLock allows 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 join with timeouts and cooperative stop flags/events.
  • threading.Event is 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

  • ProcessPoolExecutor runs 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_task schedules coroutines concurrently on the event loop.
  • Prefer gather/TaskGroup for 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

WorkloadChooseWhy
Many network callsasyncio or threadsWaits dominate; overlap them
Pure Python CPU loopprocesses / native libsGIL limits thread speedup
Simple script + few downloadsThreadPoolExecutorEasy API, enough concurrency
Shared in-memory statethreads + locks/queuesProcesses need IPC
Deterministic teaching demoscollect then sort/printAvoid interleaved races in output
L3

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.

L4

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())
L5

Problem Solving Tricks

  • Never print unordered thread logs in tutorials — collect, sort, then print for stable output.
  • ex.map preserves input order in results; as_completed does not.
  • Protect every read-modify-write on shared mutables with the same lock.
  • Prefer queue.Queue over locked lists for producer/consumer.
  • Use if __name__ == "__main__": guards with ProcessPoolExecutor on Windows.
  • asyncio.gather(*tasks) returns results in the same order as the input awaitables.
  • Set stop Events instead of killing threads.
  • CPU-bound? Measure before adding threads — the GIL may make them slower.
  • join() without a prior start() pattern check is a common hang cause — always start all, then join all.
  • Keep locks ordered (a then b everywhere) to avoid deadlocks.
L6

Practice Programs List

  1. Bump a shared counter with and without a lock; explain the wrong totals.
  2. Download-shaped demo: simulate I/O with time.sleep in a thread pool and collect timings on the main thread.
  3. Rewrite a thread pool example using asyncio.gather and asyncio.sleep(0).
  4. Build a worker pool that stops via threading.Event.
  5. Create a deadlock on purpose with two locks, then fix lock order.
  6. Use ProcessPoolExecutor to compute prime counts for several ranges and print a sorted table.
  7. Implement producer/consumer where the consumer sorts batches before appending to a result list.
  8. Offload a blocking function from async code with asyncio.to_thread.