π§΅ Threading & Multiprocessing
in Python
Understand Python threads, locks, queues, thread pools, multiprocessing and process pools, I/O-bound versus CPU-bound work, and how to avoid race conditions.
What this lesson is about
Sooner or later a Python program feels slow. Sometimes it is slow because it sits waiting: for a web server to answer, for a disk, for a database. Other times it is slow because it is crunching numbers and one processor core is working flat out while the rest of your machine idles. These are two different problems, and Python gives you two different tools for them: threads for waiting, processes for computing.
Concurrency is also where beginners meet their first truly confusing bugs. A counter that ends at the wrong number, a program that hangs forever, a script that spawns itself in an endless loop on Windows. Almost every one of these comes from a handful of ideas: shared state, the order in which things interleave, and what a process can and cannot share with its parent. If you understand those ideas, the library calls are the easy part.
A note about this page: your browser cannot create real operating-system threads or processes for Python, so the real threading and multiprocessing examples are marked as run-on-your-computer. To make sure you can still experiment, I built small runnable models: a tiny scheduler written with generators, a race condition you can watch step by step, a deterministic lock, and a fake executor. Run those, change the numbers, then copy the real versions to your own machine and see the same ideas with real threads.
What you will learn
- βTell I/O-bound work apart from CPU-bound work, and pick threads or processes accordingly
- βStart and join threads with
threading.Thread - βSee exactly how a race condition loses updates, and fix it with a
Lock - βUse
RLockandqueue.Queuefor safe cooperation between threads - βRun many tasks with
ThreadPoolExecutorand read results from futures - βUse
multiprocessing.PoolandProcessPoolExecutorfor CPU-heavy jobs - βProtect your entry point with
if __name__ == "__main__":and know why it matters - βUnderstand what the free-threaded Python build changes, and what it does not
Why programmers should learn this
- β Programs that talk to networks or disks spend most of their time waiting; threads let that waiting overlap, which can turn minutes of sequential requests into seconds.
- β CPU-heavy jobs such as image processing, simulations or parsing large files can use every core through processes, which is often the cheapest speed-up available.
- β Race conditions are among the hardest bugs to reproduce, so learning to prevent them by design (queues, locks, no shared state) saves far more time than debugging them later.
- β Web servers, task runners and data pipelines all use these building blocks internally, so understanding them helps you read framework documentation and tune worker settings sensibly.
- β Choosing the wrong tool is a common and expensive mistake: threads on a CPU-bound job gain almost nothing in standard CPython, and processes for tiny tasks cost more than they save.
Waiting versus computing: I/O-bound and CPU-bound
Before writing any concurrent code I always ask one question: what is this program actually spending its time on? If it spends it waiting (network requests, file reads, database queries, time.sleep), the work is I/O-bound. The processor is idle during those waits, so another task can use the time. If it spends it calculating (looping over numbers, compressing, encrypting, parsing), the work is CPU-bound, and the only way to go faster is to use more than one core at the same moment.
Concurrency means several tasks are in progress during the same period. Parallelism means they are literally executing at the same instant on different cores. Threads give you concurrency in every case, but in standard CPython only one thread runs Python bytecode at a time (the subject of the next lesson on the GIL and memory). That is fine when threads mostly wait, because a waiting thread releases the interpreter for others. It is useless for pure number crunching. Processes each have their own interpreter, so they run in parallel.
The example below is a model, not real threading, so it runs here in the browser. Each task is a generator that yields what it wants to do next: ("io", ticks) for waiting or ("cpu", ticks) for computing. A small scheduler keeps a virtual clock. Waiting overlaps freely, but computing needs a free core, and I let you choose how many cores exist. With one core the CPU work queues up, which is the thread situation; with four cores it spreads out, which is the process situation. Nothing is timed, so the output is the same every run.
import heapq
def make_task(*steps):
for step in steps:
yield step
def run(tasks, cores):
clock = 0
core_free = [0] * cores
ready = [(0, i, t) for i, t in enumerate(tasks)]
heapq.heapify(ready)
while ready:
when, i, task = heapq.heappop(ready)
clock = max(clock, when)
try:
kind, ticks = next(task)
except StopIteration:
continue
if kind == "io":
wake = clock + ticks
else:
c = core_free.index(min(core_free))
start = max(clock, core_free[c])
core_free[c] = start + ticks
wake = core_free[c]
heapq.heappush(ready, (wake, i, task))
return clock
def io_jobs():
return [make_task(("io", 3), ("io", 2)) for _ in range(4)]
def cpu_jobs():
return [make_task(("cpu", 5)) for _ in range(4)]
print("one after another, I/O :", 4 * 5)
print("overlapped, I/O :", run(io_jobs(), cores=1))
print("overlapped, CPU, 1 core:", run(cpu_jobs(), cores=1))
print("overlapped, CPU, 4 core:", run(cpu_jobs(), cores=4))one after another, I/O : 20 overlapped, I/O : 5 overlapped, CPU, 1 core: 20 overlapped, CPU, 4 core: 5
Line by line
- 1-4A task is a generator. Each
yieldannounces the next step: a kind (ioorcpu) and how many ticks it takes. - 6-9
runsimulates a scheduler.core_freerecords when each core becomes free;readyis a priority queue of tasks ordered by when they can continue. - 10-14Pop the task that wakes earliest, move the clock forward, and ask it for its next step. When the generator ends the task is finished.
- 15-16Waiting needs no core, so any number of tasks can wait at once: the task just wakes
tickslater. - 17-21Computing needs a core. Pick the core that frees up first, start when both the task and the core are ready, and block that core until the work finishes.
- 26-30Four I/O jobs of 5 ticks each would take 20 ticks one after another. Four CPU jobs of 5 ticks each.
- 32-35I/O overlaps completely (5 ticks) even on one core. CPU work on one core stays serial (20 ticks), but four cores finish in 5.
Read the last three lines carefully, because they are the whole decision in miniature. Overlapped waiting is a big win regardless of cores. Computing only improves when there are more cores to run on. A thread pool in CPython behaves like the one-core line for computation and like the overlapped line for waiting; a process pool behaves like the four-core line.
The model ignores the cost of starting a process or copying data to it. Real processes take noticeable time to start, so tiny tasks can run slower in a pool than in a plain loop.
Starting and joining threads
A thread is a separate path of execution inside the same process, and all threads share the same memory. You create one with threading.Thread(target=function, args=(...)), call .start() to launch it, and call .join() to wait until it finishes. If you forget to join, your main program may carry on (or exit) before the work is done.
Sharing memory is what makes threads cheap and convenient, but it is also the source of every problem in the next sections. In the example I make each thread write its answer into its own slot of a pre-sized list. Because no two threads touch the same slot, there is nothing to fight over, and the output is the same every time. Designing work so that threads do not share writable data is the simplest form of thread safety.
The block is marked as run-on-your-computer because browsers cannot start Python threads. Copy it, run it, and then try changing the range to 10 and see that the order of the result list never changes even though the threads finish in an unpredictable order.
import threading
results = [None] * 4
def worker(i):
results[i] = i * i
threads = [threading.Thread(target=worker, args=(i,)) for i in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print(results)[0, 1, 4, 9]
Line by line
- 3A list with one empty slot per thread, created before any thread starts.
- 5-6The function each thread runs. It writes only to slot
i, so threads never collide. - 8Create four
Threadobjects (not started yet), each with its own argument.argsmust be a tuple, hence the trailing comma. - 9-10
start()launches each thread. From here they run concurrently with the main thread. - 11-12
join()blocks until a thread finishes. Joining all of them guaranteesresultsis complete before we print.
Pass work in through args and get results out through slots, queues or futures. Avoid having threads share a single variable they all modify.
Race conditions, step by step
Here is the classic bug. counter += 1 looks like one action, but the interpreter performs three: read the current value, add one, write the result back. If two threads each do this, the operating system may switch between them in the middle. Thread A reads 0, thread B reads 0, A writes 1, B writes 1. Two increments happened and the counter says 1. One update was lost. That is a race condition: the result depends on the unlucky timing of the switch.
Real races are rare and hard to reproduce, which is exactly why they are dangerous. So instead of hoping to catch one, let me show you one deliberately. I model each worker as a generator and put a yield between each of the three steps. The yield is the point where the scheduler may switch to someone else. A round-robin scheduler resumes each worker in turn, so the interleaving is the same every run and you can see precisely how the update is lost.
Then I add a lock model. The worker must acquire the lock before it reads, and must release after it writes. While one worker holds it, the others politely wait by yielding. The same scheduler, the same three workers, and now the total is correct. This is what threading.Lock does for you in real programs, with the operating system handling the waiting.
def increment(shared, name):
local = shared["n"]
print(f"{name} read {local}")
yield
local += 1
yield
shared["n"] = local
print(f"{name} wrote {local}")
def round_robin(workers):
active = list(workers)
while active:
for w in list(active):
try:
next(w)
except StopIteration:
active.remove(w)
shared = {"n": 0}
round_robin([increment(shared, "A"), increment(shared, "B")])
print("expected 2, got", shared["n"])A read 0 B read 0 A wrote 1 B wrote 1 expected 2, got 1
Line by line
- 1-8One increment broken into read, add and write. The
yieldstatements are the places where another worker could run. - 10-16A minimal scheduler: give every worker one step in turn and drop each one when it finishes.
- 18-20Both workers read 0 before either writes, so both write 1. One increment vanishes.
class SimLock:
def __init__(self):
self.owner = None
def acquire(self, who):
if self.owner is None:
self.owner = who
return True
return False
def release(self, who):
assert self.owner == who
self.owner = None
def safe_increment(shared, lock, name):
while not lock.acquire(name):
yield
local = shared["n"]
yield
local += 1
yield
shared["n"] = local
lock.release(name)
def round_robin(workers):
active = list(workers)
while active:
for w in list(active):
try:
next(w)
except StopIteration:
active.remove(w)
shared = {"n": 0}
lock = SimLock()
round_robin([safe_increment(shared, lock, c) for c in "ABC"])
print("expected 3, got", shared["n"])expected 3, got 3
Line by line
- 1-11A deterministic lock: only one owner at a time.
acquirereturns False if someone else holds it. - 13-21The worker keeps yielding while it cannot get the lock. Once it has it, the read-add-write sequence cannot be interleaved with another worker's.
- 23-29The same round-robin scheduler as before.
- 31-34Three workers now produce exactly 3, because each one completes its whole read-add-write before the next begins.
A race is a property of the code, not of how often it fails. Code that works on your laptop a thousand times can still be wrong. Reason about shared data instead of testing your way to confidence.
Lock, RLock and Queue in real code
A real threading.Lock works like the model: with lock: acquires it on entry and releases it on exit even if an exception is raised, so always prefer the with form over manual acquire and release. Keep the locked section as short as you can, because every other thread that needs the lock is stuck until you leave. The static example below runs four threads that each add 10,000 to a shared counter under a lock, and the answer is always 40,000.
An ordinary Lock is not re-entrant: if the thread that holds it tries to acquire it again, it blocks forever and deadlocks itself. An RLock remembers its owner and a count, so the same thread may acquire it several times, which matters when one locked method calls another locked method. The runnable block after it shows both behaviours in one thread by using acquire(blocking=False), which returns immediately instead of waiting, so nothing hangs.
My favourite way to avoid locks altogether is queue.Queue. A queue is already thread-safe: producers put items in, consumers get them out, and the queue does the locking. Passing messages instead of sharing variables turns most race conditions into simple data flow. The runnable block demonstrates the three queue flavours and the Empty exception with no threads at all, and the static block at the end has a real producer and consumer joined by a bounded queue.
import threading
counter = 0
lock = threading.Lock()
def work(n):
global counter
for _ in range(n):
with lock:
counter += 1
threads = [threading.Thread(target=work, args=(10_000,)) for _ in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
print(counter)40000
Line by line
- 3-4A module-level counter and the lock that guards it.
- 6-10Each thread increments the counter 10,000 times.
with lock:makes the read-add-write atomic with respect to the other threads. - 12-16Start four threads and join them all.
- 17Always 40000. Without the lock, the total can come out lower on some runs.
import queue
import threading
lock = threading.Lock()
lock.acquire()
print("Lock, second acquire possible?", lock.acquire(blocking=False))
lock.release()
rlock = threading.RLock()
rlock.acquire()
print("RLock, second acquire possible?", rlock.acquire(blocking=False))
rlock.release()
rlock.release()
fifo = queue.Queue()
lifo = queue.LifoQueue()
prio = queue.PriorityQueue()
for item in (3, 1, 2):
fifo.put(item)
lifo.put(item)
prio.put(item)
print([fifo.get() for _ in range(3)])
print([lifo.get() for _ in range(3)])
print([prio.get() for _ in range(3)])
try:
fifo.get_nowait()
except queue.Empty:
print("queue is empty")Lock, second acquire possible? False RLock, second acquire possible? True [3, 1, 2] [2, 1, 3] [1, 2, 3] queue is empty
Line by line
- 5-7Take a plain lock, then try to take it again without waiting. It says no, because a
Lockdoes not know who owns it. A blocking second acquire here would hang forever. - 9-13An
RLockallows the owner to acquire again, so the answer is yes. It must be released as many times as it was acquired. - 15-21Three queue types, filled with the same items in the same order.
- 22-24FIFO returns 3, 1, 2 (first in, first out); LIFO reverses it; the priority queue returns the smallest first.
- 26-29
get_nowaitraisesqueue.Emptyinstead of waiting, which is useful for polling.
import queue
import threading
q = queue.Queue(maxsize=2)
DONE = object()
def producer():
for n in range(5):
q.put(n)
q.put(DONE)
def consumer():
while True:
item = q.get()
if item is DONE:
break
print("got", item * 10)
p = threading.Thread(target=producer)
c = threading.Thread(target=consumer)
p.start()
c.start()
p.join()
c.join()got 0 got 10 got 20 got 30 got 40
Line by line
- 4-5A bounded queue:
putblocks when two items are waiting, which stops a fast producer from flooding memory.DONEis a unique sentinel object. - 7-10The producer sends five numbers, then the sentinel to say there is nothing more.
- 12-17The consumer loops forever, pulling items. When it sees the sentinel it stops. Only one consumer reads, so the order is preserved.
- 19-24Start both threads and wait for both. The queue handles all locking between them.
Thread pools and futures
Creating threads by hand is fine for learning, but in real code I almost always reach for concurrent.futures.ThreadPoolExecutor. It owns a fixed set of worker threads, accepts tasks, and hands you a future for each: an object that will eventually contain the result (or the exception). pool.map(fn, items) gives results in input order, while pool.submit(fn, arg) returns a future immediately and as_completed yields futures in the order they finish.
A future also carries failures. If the function raises, the exception is stored and re-raised when you call future.result(). That is a big improvement over a bare thread, where an exception just prints a traceback and the thread dies quietly. The with block waits for all submitted work to finish before leaving, so you do not need to join anything.
The first block is real and run-on-your-computer. Each fake download sleeps for a fifth of a second, so four tasks finish in roughly the time of one rather than four. The second block is a fake executor that runs everything synchronously but speaks the same interface, using the real Future class, which works fine without threads. It is good for understanding the API in the browser and, in a real project, for testing code that normally uses a pool, because a synchronous executor makes tests deterministic.
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
def fetch(name):
time.sleep(0.2)
return f"{name}: done"
names = ["a", "b", "c", "d"]
with ThreadPoolExecutor(max_workers=4) as pool:
for line in pool.map(fetch, names):
print(line)
with ThreadPoolExecutor(max_workers=2) as pool:
futures = {pool.submit(fetch, n): n for n in names}
for fut in as_completed(futures):
fut.result()
print(sorted(futures[f] for f in futures))a: done b: done c: done d: done ['a', 'b', 'c', 'd']
Line by line
- 4-6A stand-in for slow I/O.
sleepreleases the interpreter so other threads run during the wait. - 9-11
maprunsfetchfor every name on four threads and yields results in the original order. - 13-17
submitreturns a future per task; a dict remembers which name belongs to which.as_completedhands them back as they finish, andresult()re-raises any exception from the task. - 18Sorting makes the printed list the same whatever the completion order was.
from concurrent.futures import Future
class SyncExecutor:
"""Same shape as ThreadPoolExecutor, but runs each task immediately."""
def submit(self, fn, *args):
fut = Future()
try:
fut.set_result(fn(*args))
except Exception as exc:
fut.set_exception(exc)
return fut
def map(self, fn, items):
return [self.submit(fn, x).result() for x in items]
def __enter__(self):
return self
def __exit__(self, *exc_info):
return False
def parse(text):
return int(text) * 2
with SyncExecutor() as pool:
print(pool.map(parse, ["1", "2", "3"]))
good = pool.submit(parse, "21")
bad = pool.submit(parse, "x")
print(good.result(), good.done())
print(type(bad.exception()).__name__)
try:
bad.result()
except ValueError:
print("error re-raised from the future")[2, 4, 6] 42 True ValueError error re-raised from the future
Line by line
- 1-12
submitcreates a realFuture, runs the function immediately and stores either the result or the exception on it. - 14-15
mapruns every item and returns results in order. - 17-21Context-manager methods so it can be used in a
withblock just like the real pool. - 23-24A function that fails for non-numeric text.
- 26-33Successful futures hold their value, failed futures hold the exception, and
result()re-raises it, exactly like a real pool.
Processes for CPU-bound work
When the job is computation, use processes. Each process is a separate Python interpreter with its own memory and its own GIL, so on a four-core machine four processes really do run four calculations at once. multiprocessing.Pool offers map much like the thread pool, and concurrent.futures.ProcessPoolExecutor offers the same futures interface as ThreadPoolExecutor, so switching between threads and processes can be a one-word change.
The cost is that processes do not share memory. Arguments and return values are pickled (serialised), sent through a pipe, and unpickled on the other side. That means the function you send must be importable by name (a top-level function, not a lambda or a function defined inside another function) and your data must be picklable. It also means sending huge objects back and forth can cost more than the computation itself. Send small inputs, return small outputs, and give each task enough work to be worth the trip.
Both examples below are real and run-on-your-computer. They count primes with a deliberately slow function, which is pure CPU work. The expected results are fixed, so you can check them, but the speed-up you see depends on how many cores you have. Notice the if __name__ == "__main__": guard in each; the next section explains why it is not optional.
from multiprocessing import Pool
def is_prime(n):
if n < 2:
return False
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
def count_primes(limit):
return sum(1 for n in range(limit) if is_prime(n))
if __name__ == "__main__":
limits = [10_000, 20_000, 30_000, 40_000]
with Pool(processes=4) as pool:
print(pool.map(count_primes, limits))[1229, 2262, 3245, 4203]
Line by line
- 3-11Trial division, a classic CPU-bound loop.
- 13-14One task: count the primes below a limit. It is a top-level function so child processes can import it.
- 16The guard: only the original process runs the code beneath it.
- 17-19Create a pool of four worker processes and map the function over four inputs. Results come back in order.
from concurrent.futures import ProcessPoolExecutor
def heavy(n):
return sum(i * i for i in range(n))
def main():
jobs = [100_000, 200_000, 300_000]
with ProcessPoolExecutor() as pool:
for n, total in zip(jobs, pool.map(heavy, jobs)):
print(n, total)
if __name__ == "__main__":
main()100000 333328333350000 200000 2666646666700000 300000 8999955000050000
Line by line
- 3-4A CPU-bound task that sums squares. It returns one integer, which is cheap to send back.
- 6-10
mainbuilds the pool (the default size is the number of CPU cores) and pairs each job with its result. - 12-13Keep the real work inside
main()and call it only from the guarded block.
For a first speed-up, try Pool or ProcessPoolExecutor with the default size, then measure with time.perf_counter() on your own machine. Measure; do not guess.
The __main__ guard and what processes can share
On Windows and macOS, new processes are started with the spawn method (Linux has historically used fork, and newer Python versions are moving away from it, so write code that works with spawn): the child is a fresh interpreter that imports your main module to find the functions it must run. If that module creates a pool at the top level, the child would import it, create its own pool, and spawn grandchildren in an endless chain. Python detects this and raises a RuntimeError, but the fix is yours to make: put the pool creation behind if __name__ == "__main__":. Children import your module under the name __mp_main__, so the guarded block is skipped for them.
The runnable block below simulates that import so you can see the mechanism without any processes. It also tests the pickle rule: a top-level function survives a pickle round trip, while a lambda does not. When a pool raises a baffling pickling error, this is nearly always the reason.
Finally, remember that a child works on a copy. If you append to a list inside a worker process, the parent's list is untouched. The second block imitates this with a pickle round trip. To genuinely share state between processes you need explicit tools (multiprocessing.Queue, Value, Manager, shared memory), and I would treat them as a last resort. Returning results from workers and combining them in the parent is simpler and safer.
import pickle
def module_body(dunder_name):
print("module imported as", dunder_name)
if dunder_name == "__main__":
print(" -> create the pool here")
else:
print(" -> child process: skip the pool")
module_body("__main__")
module_body("__mp_main__")
def square(x):
return x * x
clone = pickle.loads(pickle.dumps(square))
print(clone(7))
try:
pickle.dumps(lambda x: x * x)
except Exception:
print("a lambda cannot be pickled")module imported as __main__ -> create the pool here module imported as __mp_main__ -> child process: skip the pool 49 a lambda cannot be pickled
Line by line
- 3-8A model of a module being imported. Only the name
__main__takes the branch that creates the pool. - 10-11The original program is
__main__; a spawned child imports the same file as__mp_main__, so it skips the pool. - 13-17A top-level function pickles by name, so a child process can find it again and call it.
- 19-22A lambda has no importable name, so pickling fails. Use a top-level
deffor pool tasks.
import pickle
parent_data = {"scores": [1, 2, 3]}
def child_job(data):
data["scores"].append(99)
return sum(data["scores"])
child_copy = pickle.loads(pickle.dumps(parent_data))
print("child result:", child_job(child_copy))
print("parent still has:", parent_data["scores"])
chunks = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
partials = [sum(chunk) for chunk in chunks]
print(partials, sum(partials))child result: 105 parent still has: [1, 2, 3] [6, 15, 24] 45
Line by line
- 3-7Some parent data, and a job that mutates the dictionary it receives.
- 9-11A process receives a pickled copy, so the append happens to the copy and the parent's list keeps its three values.
- 13-15The healthy pattern: split data into chunks, let each worker return a small partial result, and combine the partials in the parent.
Choosing the right tool, and the free-threaded build
Here is the decision I walk through. Mostly waiting on many connections or files, with Python glue in between: threads (ThreadPoolExecutor) or, for thousands of connections, async code. Heavy computation in pure Python: processes. Heavy computation inside a compiled library such as NumPy: often threads are enough, because such libraries usually release the GIL while they compute. A few tiny tasks: probably none of these, just a plain loop.
A recent change deserves an honest, careful note. Python 3.13 introduced an optional, experimental free-threaded build (usually installed as python3.13t) in which the GIL is removed so threads can run Python code in parallel. In Python 3.14 that build is officially supported but still optional, and the standard build you get by default keeps the GIL. Single-threaded programs can be a bit slower on the free-threaded build, and some C extension packages need updates before they work well on it. So for now, treat it as something to try deliberately, not as the new default. Check the current documentation for your Python version before relying on it.
Even if you run on a free-threaded build, everything in this lesson about race conditions still applies, and it applies more strongly. Locks, queues and avoiding shared mutable state are not workarounds for the GIL; they are how correct concurrent programs are written. The block below is a small static snippet to see which build you are on.
import sys
import sysconfig
print(sys.version)
print("free-threaded build:", bool(sysconfig.get_config_var("Py_GIL_DISABLED")))
check = getattr(sys, "_is_gil_enabled", None)
if check is not None:
print("GIL currently enabled:", check())
else:
print("This Python predates the free-threaded work (before 3.13)")Line by line
- 4The full version string of the interpreter.
- 5
Py_GIL_DISABLEDis set in free-threaded builds. It isNoneotherwise, sobool()turns it into True or False. - 7-11
sys._is_gil_enabled()exists from 3.13 and tells you whether the GIL is on right now. On older versions the attribute is missing, so we usegetattrwith a default.
def choose_tool(waits_on, task_count):
if task_count < 4:
return "plain loop: too few tasks to bother"
if waits_on == "io":
return "ThreadPoolExecutor (or async for thousands)"
if waits_on == "cpu":
return "ProcessPoolExecutor / multiprocessing.Pool"
return "measure first"
for kind, n in [("io", 100), ("cpu", 8), ("cpu", 2), ("unknown", 50)]:
print(f"{kind:8} x{n:<4} -> {choose_tool(kind, n)}")io x100 -> ThreadPoolExecutor (or async for thousands) cpu x8 -> ProcessPoolExecutor / multiprocessing.Pool cpu x2 -> plain loop: too few tasks to bother unknown x50 -> measure first
Line by line
- 1-9A rule of thumb as code: few tasks need no concurrency, waiting suggests threads, computing suggests processes, and anything unclear should be measured.
- 11-12Try four situations. Edit the list to match your own jobs.
Common mistakes
β Using threads to speed up CPU-bound code
In standard CPython only one thread executes Python bytecode at a time, so a pure-Python calculation split across threads is no faster, and can be slower. Use processes for that, or move the hot loop into a compiled library.
β Forgetting the if __name__ == "__main__": guard
With the spawn start method, each child re-imports your module. Without the guard it tries to create more pools and fails with a RuntimeError, or appears to run your script repeatedly. Guard the entry point every time you use multiprocessing or ProcessPoolExecutor.
β Modifying a shared variable without a lock
counter += 1 is read, add, write. Two threads can interleave and lose an update, and it will only fail occasionally. Protect shared writes with with lock:, or better, pass messages through a queue.Queue.
β Expecting worker processes to change the parent's data
Each process has its own memory. Appending to a list in a child changes only the child's copy. Return results from the worker and combine them in the parent.
β Sending lambdas or nested functions to a process pool
Pool tasks are pickled by name, so they must be top-level functions of an importable module. A lambda or inner function fails with a pickling error.
Quick quiz
Tap an answer. I explain every one, right or wrong.
Q1. A script downloads 200 small files, mostly waiting on the network. Which is the best first choice?
Q2. Two threads run counter += 1 on a shared integer with no lock. What can happen?
Q3. What happens if the thread that holds a plain threading.Lock blocks on acquiring it again?
Lock is not re-entrant, so the owner waits for a release that only it could perform. Use RLock when the same thread must re-acquire.Q4. Why do children not run the code under if __name__ == "__main__":?
__mp_main__, so the __name__ == "__main__" test is false and the pool-creating code is skipped.Q5. Which function can be sent to a ProcessPoolExecutor reliably?
Q6. Which statement about the free-threaded Python build is most accurate?
Frequently asked questions
Is Python multithreading useless because of the GIL?
+No. The GIL limits how many threads run Python bytecode at once, but a thread that is waiting for I/O releases it, so threads are very effective for network and disk work. They just do not speed up pure-Python computation. See the GIL lesson for the details.
How many threads or processes should I use?
+For processes, start with the number of CPU cores, which is the default for ProcessPoolExecutor. For I/O threads, the useful number depends on the server or disk you are talking to, so begin with a modest number such as 8 to 32, measure, and adjust. More is not automatically faster.
Should I use threads or async?
+Both suit I/O-bound work. Threads are easier to add to existing blocking code. Async scales to far more simultaneous connections but requires async-aware libraries throughout. For a handful of tasks, threads are usually the simpler choice.
How do I stop a running thread?
+Python has no safe way to kill a thread from outside. Make the thread check a threading.Event regularly and exit when it is set, or send it a sentinel value through its queue.
Why does my pool example hang or crash in a Jupyter notebook or on Windows?
+Usually because of the spawn start method: functions defined interactively cannot be imported by the child, or the guard is missing. Put task functions in a separate .py module, import them, and keep pool creation inside if __name__ == "__main__":.
Key takeaways
- βAsk whether the job is waiting (I/O-bound) or computing (CPU-bound) before choosing a tool.
- βThreads share memory and suit I/O-bound work; processes have separate memory and suit CPU-bound work.
- βA race condition is an unlucky interleaving of read, modify and write; fix it with a
Lock, aQueueor by not sharing mutable data. - βPrefer
with lock:and keep locked sections short; useRLockonly when the same thread must re-acquire. - βUse
ThreadPoolExecutororProcessPoolExecutorand read results from futures, which also carry exceptions. - βGuard process-spawning code with
if __name__ == "__main__":, send picklable top-level functions, and treat free-threaded Python as optional.