Python Multithreading & Multiprocessing Cheat Sheet
Concurrent Python covering threading basics, locks, executor pools, multiprocessing, and when to choose threads versus processes.
2 PagesAdvancedApr 8, 2026
Basic Threading
Starting and joining threads with the threading module.
python
import threadingdef worker(n): print(f"Worker {n} running")threads = []for i in range(3): t = threading.Thread(target=worker, args=(i,)) t.start() threads.append(t)for t in threads: t.join() # wait for all threads to finish
Locks & Synchronization
Protecting shared state from race conditions.
python
lock = threading.Lock()counter = 0def increment(): global counter with lock: # only one thread at a time in this block counter += 1threads = [threading.Thread(target=increment) for _ in range(100)]for t in threads: t.start()for t in threads: t.join()
ThreadPoolExecutor / ProcessPoolExecutor
A higher-level API for managing worker pools.
python
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutordef square(n): return n * nwith ThreadPoolExecutor(max_workers=4) as executor: results = list(executor.map(square, range(10)))with ProcessPoolExecutor(max_workers=4) as executor: futures = [executor.submit(square, i) for i in range(10)] results = [f.result() for f in futures]
Multiprocessing with Pool
Running CPU-bound work in separate processes to bypass the GIL.
python
from multiprocessing import Pooldef square(n): return n * nif __name__ == "__main__": # required on Windows/macOS spawn start method with Pool(processes=4) as pool: results = pool.map(square, range(10)) print(results)
Threading vs Multiprocessing
Choosing the right concurrency model.
- GIL (Global Interpreter Lock)- allows only one thread to execute Python bytecode at a time in CPython
- threading- best for I/O-bound work (network, disk) where threads spend time waiting
- multiprocessing- best for CPU-bound work since each process has its own interpreter and GIL
- Shared memory- threads share memory directly; processes need explicit IPC (Queue, Pipe, Value)
- multiprocessing.Queue- process-safe queue for passing data between processes
- multiprocessing.Manager- provides shared, synchronized objects like dicts and lists across processes
Pro Tip
Don't reach for multiprocessing by default — process creation and inter-process communication have real overhead. Profile first: use threading or asyncio for I/O-bound bottlenecks, and reserve multiprocessing for genuinely CPU-bound work that threading can't speed up due to the GIL.
Was this cheat sheet helpful?
Explore Topics
#PythonMultithreadingMultiprocessing#PythonMultithreadingMultiprocessingCheatSheet#Programming#Advanced#BasicThreading#LocksSynchronization#ThreadPoolExecutorProcessPoolExecutor#MultiprocessingWithPool#Concurrency#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech
Professional Web Designing Services
- Responsive Websites
- E-commerce Solutions
- SEO Friendly Design
- Fast & Secure
- Support & Maintenance