Interview Q&A · Python · 25 questions in this topic
Concurrency & Parallelism — Python Interview Q&A
Threads, processes and asyncio — what each one is actually good at, what the GIL prevents, and how to choose under a real workload. Part of Concurrency & Parallelism · 375 questions in the Python bank.
What is the difference between a process and a thread in Python?
Answer
A process is an independent program with its own memory space; threads are lighter-weight units of execution that run within a process and share that process's memory. In Python specifically, threads within one process are also constrained by the GIL (Q233), which limits their ability to run Python bytecode truly simultaneously.
Because threads share memory, communication between them is simple (shared variables) but requires careful synchronization to avoid race conditions (Q241). Because processes have separate memory, communication requires explicit inter-process communication (Q240), but each process gets its own independent GIL, enabling genuine parallel execution of Python code.
Example
import threading import multiprocessing def worker(): print("Working...") # Thread: shares memory with the main process t = threading.Thread(target=worker) t.start() t.join() # Process: separate memory space entirely p = multiprocessing.Process(target=worker) p.start() p.join()
💡 Immediately connect this to the GIL — "threads share memory but are limited by the GIL for CPU-bound work; processes have overhead but truly parallelize" is the one-sentence summary that sets up nearly every other question in this section.
What is the threading module, and how do you create a thread?
Answer
threading is the standard library module for creating and managing threads. You create a Thread object with a target function, call.start() to begin execution, and.join() to wait for it to finish.
.join() is essential when the main program needs to wait for background threads to complete before continuing (e.g., before the program exits) — without it, the main thread might finish and the program could terminate while background threads are still running.
Example
import threading import time def download_file(name, delay): print(f"Starting download: {name}") time.sleep(delay) # simulates an I/O-bound wait print(f"Finished download: {name}") threads = [] for name, delay in [("file1", 2), ("file2", 1), ("file3", 3)]: t = threading.Thread(target=download_file, args=(name, delay)) threads.append(t) t.start() for t in threads: t.join() # wait for all threads to finish before continuing print("All downloads complete")
💡 This exact "simulate concurrent downloads with time.sleep() " pattern is a very common way interviewers ask you to demonstrate basic threading — practice writing it fluently, including the.join() loop.
What is the Global Interpreter Lock (GIL)?
Answer
The GIL is a mutex (lock) in CPython that allows only one thread to execute Python bytecode at a time, even on a multi-core machine. This means true parallel execution of Python code across threads within a single process isn't possible in CPython — it's specific to the CPython implementation, not a fundamental property of the Python language itself.
The GIL exists primarily to simplify CPython's memory management (reference counting isn't thread-safe without some form of locking) and to make the interpreter itself easier and safer to implement — the trade-off is that CPUbound multi-threaded Python code doesn't get the speedup you'd expect from multiple cores.
Example
import threading import time def cpu_bound_work(): count = 0 for _ in range(50_000_000): count += 1 start = time.perf_counter() t1 = threading.Thread(target=cpu_bound_work) t2 = threading.Thread(target=cpu_bound_work) t1.start(); t2.start() t1.join(); t2.join() print(f"Two threads: {time.perf_counter() - start:.2f}s") # Often NOT meaningfully faster than running cpu_bound_work() twice sequentially, # because the GIL prevents true simultaneous execution of Python bytecode
💡 Explicitly say "this is a CPython implementation detail, not a Python language requirement" — other implementations (like Jython) don't have a GIL, and this distinction is exactly the kind of precision interviewers listen for.
Why does the GIL exist, and what problem does it solve?
Answer
The GIL primarily protects CPython's reference-counting memory management, Q197) from race conditions — without some form of locking, two threads simultaneously incrementing/decrementing the same object's reference count could corrupt it, leading to memory leaks or premature deallocation. The GIL is CPython's historically simple solution to this problem.
An alternative would be fine-grained locking on every individual object (as some other languages/runtimes do), but that approach is significantly more complex to implement correctly and tends to be slower for single-threaded code (which is the overwhelmingly common case) due to the overhead of acquiring/releasing many small locks constantly.
Example
# Conceptually, without a GIL, this kind of operation would need # fine-grained protection to be safe across threads: shared_list = [] def append_many(): for _ in range(100000): shared_list.append(1) # reference counting internals need protection here # The GIL provides that protection globally and simply, at the cost of # preventing true CPU-bound parallelism across threads in one process.
💡 Framing the GIL as "a deliberate simplicity-vs-parallelism trade-off made decades ago, not an oversight" shows historical and design awareness beyond just knowing the GIL exists and causes friction.
How does the GIL affect multi-threaded CPU-bound Python programs?
Answer
For CPU-bound work (heavy computation with no waiting), the GIL prevents threads from running Python bytecode truly simultaneously — so adding more threads to a CPU-bound task typically provides little to no speedup, and can sometimes even be slightly slower than a single thread due to the overhead of the GIL switching between them.
This is exactly why multiprocessing (Q237), not threading, is the standard recommendation for CPU-bound parallelism in Python — separate processes each have their own GIL, allowing genuine simultaneous execution across CPU cores.
Example
import time from concurrent.futures import ThreadPoolExecutor def cpu_bound_task(n): return sum(i * i for i in range(n)) start = time.perf_counter() with ThreadPoolExecutor(max_workers=4) as executor: results = list(executor.map(cpu_bound_task, [10_000_000] * 4)) print(f"Threads: {time.perf_counter() - start:.2f}s") # Often barely faster than doing this sequentially -- GIL bottleneck for CPU-bound work
Does the GIL affect I/O-bound multi-threaded programs the same way?
Answer
No — the GIL is released while a thread is waiting on I/O (network requests, file reads, time.sleep()), so multiple threads can make real, effective concurrent progress on I/O-bound work, even though only one can execute Python bytecode at any given instant.
This is why threading remains a genuinely useful and commonly recommended tool in Python specifically for I/O-bound concurrency (multiple network requests, multiple file operations) — the GIL constraint essentially doesn't matter here, since the bottleneck is waiting on external resources, not competing for CPU time to run Python code.
Example
import time import threading import requests # a third-party library, illustrative here def fetch(url): response = requests.get(url) # GIL is released while waiting for the network return response.status_code urls = ["https://example.com"] * 10 start = time.perf_counter() threads = [threading.Thread(target=fetch, args=(url,)) for url in urls] for t in threads: t.start() for t in threads: t.join() print(f"Threaded I/O-bound: {time.perf_counter() - start:.2f}s") # Genuinely much faster than fetching all 10 URLs sequentially, one at a time
💡 This is the crucial nuance that separates a shallow "the GIL makes Python threading useless" answer from a correct one — threading is entirely appropriate and effective for I/O-bound work; the GIL only becomes a real bottleneck for CPU-bound work.
What is the multiprocessing module, and how does it get around the GIL?
Answer
multiprocessing creates entirely separate operating system processes, each with its own independent Python interpreter and its own GIL — since the GIL only restricts threads within a single process, running work across multiple processes achieves genuine parallel execution of Python code across CPU cores.
The trade-off is real overhead: each process needs its own memory space, starting a process is more expensive than starting a thread, and since processes don't share memory, passing data between them requires explicit serialization (typically via pickling, tying back to through mechanisms like queues or pipes.
Example
import time from multiprocessing import Pool def cpu_bound_task(n): return sum(i * i for i in range(n)) if __name__ == "__main__": start = time.perf_counter() with Pool(processes=4) as pool: results = pool.map(cpu_bound_task, [10_000_000] * 4) print(f"Processes: {time.perf_counter() - start:.2f}s") # Genuinely faster than the threaded version -- true parallelism across cores
💡 Note the if __name__ == "__main__": guard in the example — it's specifically required for multiprocessing on some platforms (notably Windows) since child processes re-import the main module, and without the guard this can trigger infinite recursive process spawning.
What is the difference between threading and multiprocessing in Python?
Answer
threading creates lightweight threads sharing one process's memory, well-suited to I/O-bound work but limited by the GIL for CPU-bound work. multiprocessing creates separate, heavier-weight processes with independent memory and independent GILs, achieving true parallelism for CPU-bound work at the cost of higher memory usage and more complex inter-process communication.
Key points
- 1Memory — threading: Shared across threads; multiprocessing: Separate per process
- 2GIL impact — threading: Limits CPU-bound parallelism; multiprocessing: Bypassed — each process has its own GIL
- 3Best for — threading: I/O-bound work; multiprocessing: CPU-bound work
- 4Overhead — threading: Low (lightweight); multiprocessing: Higher (separate interpreter, memory)
- 5Communication — threading: Direct (shared variables, needs locks); multiprocessing: Explicit (queues, pipes, requires serialization)
Example
# Rule of thumb, encoded directly: def choose_concurrency_tool(is_cpu_bound: bool) -> str: if is_cpu_bound: return "multiprocessing -- needs true parallelism across cores" else: return "threading (or asyncio) -- I/O waits release the GIL anyway"
💡 This comparison table question is a very common "explain the trade-off" interview staple — practice stating the decision rule ("CPU-bound → multiprocessing, I/O-bound → threading/asyncio") confidently and immediately, then backing it up with the GIL explanation.
What are the trade-offs of using multiprocessing?
Answer
You gain true parallel CPU execution, but pay for it with higher memory usage (each process has its own full copy of the Python interpreter and relevant data), slower startup time per worker, and the requirement that shared data be explicitly serialized (pickled) to pass between processes rather than accessed directly.
Because data must be pickled to cross process boundaries, not everything can be easily shared this way — objects that can't be pickled (like open file handles, certain locks, or some complex custom objects) require special handling or restructuring to work with multiprocessing.
Example
from multiprocessing import Process, Value, Array def increment(shared_counter): for _ in range(1000): with shared_counter.get_lock(): # explicit locking needed even across processes shared_counter.value += 1 if __name__ == "__main__": counter = Value("i", 0) # a specially shared memory value, not a plain Python int processes = [Process(target=increment, args=(counter,)) for _ in range(4)] for p in processes: p.start() for p in processes: p.join() print(counter.value) # 4000 -- required special shared-memory types, not plain variables
💡 Highlighting that you can't just share a plain Python variable across processes the way you can across threads — you need special constructs like Value / Array / Manager — is a concrete, specific trade-off that shows real hands-on multiprocessing experience.
How do separate processes communicate with each other using multiprocessing?
Answer
Since processes don't share memory, multiprocessing provides explicit inter-process communication (IPC) primitives: Queue (thread-and-process-safe FIFO queue) and Pipe (a two-way communication channel between exactly two processes) are the two most commonly used.
Queue is generally preferred for coordinating multiple worker processes (a common producer/consumer pattern), while Pipe is more appropriate for a simple, direct communication channel between exactly two related processes.
Example
from multiprocessing import Process, Queue def worker(q, n): result = n * n q.put(result) # send data back to the main process if __name__ == "__main__": q = Queue() processes = [Process(target=worker, args=(q, i)) for i in range(5)] for p in processes: p.start() for p in processes: p.join() results = [q.get() for _ in range(5)] print(results) # [0, 1, 4, 9, 16] (order may vary depending on completion timing)
💡 Mentioning that Queue here is specifically the multiprocessing.Queue (safe across process boundaries), not the same class as queue.Queue (thread-safe only, within one process) — is a small but precise detail worth stating explicitly.
What is a race condition, and how do you prevent one in Python?
Answer
A race condition occurs when multiple threads (or processes) access and modify shared data concurrently, and the final result depends unpredictably on the exact timing of their execution. You prevent it by synchronizing access with a lock (threading.Lock), ensuring only one thread modifies the shared data at a time.
Even a seemingly simple operation like counter += 1 isn't atomic at the bytecode level — it involves reading the current value, computing the new value, and writing it back, as three separate steps. If two threads interleave these steps, one thread's update can be silently lost.
Example
import threading counter = 0 def increment_unsafe(): global counter for _ in range(100000): counter += 1 # NOT atomic -- read, add, write, as 3 separate steps threads = [threading.Thread(target=increment_unsafe) for _ in range(4)] for t in threads: t.start() for t in threads: t.join() print(counter) # Often LESS than 400000 -- lost updates due to the race condition! # Fixed with a lock: lock = threading.Lock() counter_safe = 0 def increment_safe(): global counter_safe for _ in range(100000): with lock: # only one thread can be inside this block at a time counter_safe += 1 threads = [threading.Thread(target=increment_safe) for _ in range(4)] for t in threads: t.start() for t in threads: t.join() print(counter_safe) # Reliably 400000
What is a deadlock, and how does it happen?
Answer
A deadlock occurs when two or more threads are each waiting for a resource (typically a lock) held by the other, so none of them can ever proceed — the program hangs indefinitely. The classic cause is two threads acquiring the same two locks in opposite order.
The standard prevention strategy is to always acquire multiple locks in a consistent, globally agreed-upon order across every thread — if every thread always locks resource A before resource B, the circular waiting condition that causes deadlock simply can't arise.
Example
import threading import time lock_a = threading.Lock() lock_b = threading.Lock() def thread_1(): with lock_a: time.sleep(0.1) # gives thread_2 time to grab lock_b with lock_b: # thread_1 now wants lock_b... print("Thread 1 acquired both locks") def thread_2(): with lock_b: time.sleep(0.1) with lock_a: # ...while thread_2 wants lock_a -- DEADLOCK print("Thread 2 acquired both locks") # Fix: both threads should acquire locks in the SAME order (e.g., always A before B) def thread_1_fixed(): with lock_a: with lock_b: print("Thread 1 (fixed) acquired both locks") def thread_2_fixed(): with lock_a: # same order as thread_1_fixed -- no circular wait possible with lock_b: print("Thread 2 (fixed) acquired both locks")
💡 "Always acquire multiple locks in a consistent order across the entire codebase" is the specific, actionable prevention strategy interviewers want to hear — not just "be careful with locks."
What are locks (threading.Lock), and how do you use them?
Answer
A Lock is a synchronization primitive that only one thread can hold at a time — other threads attempting to acquire it will block until it's released. Using it as a context manager (with lock:) is the idiomatic approach, guaranteeing release even if an exception occurs inside the protected block.
Locks should protect the smallest critical section possible — locking too broadly (holding a lock during slow, unrelated work) unnecessarily serializes your program and defeats much of the purpose of using threads in the first place.
Example
import threading balance_lock = threading.Lock() balance = 1000 def withdraw(amount): global balance with balance_lock: # only one thread can be in here at a time if balance >= amount: balance -= amount print(f"Withdrew {amount}, balance now {balance}") else: print("Insufficient funds") threads = [threading.Thread(target=withdraw, args=(200,)) for _ in range(6)] for t in threads: t.start() for t in threads: t.join()
💡 Emphasize using with lock: over manual.acquire() /.release() calls — exactly the same "guaranteed cleanup even on exception" reasoning as with open(.) from, applied to synchronization instead of file handles.
How do you use concurrent.futures.ThreadPoolExecutor?
Answer
ThreadPoolExecutor manages a pool of worker threads for you, letting you submit tasks (.submit()) or map a function over an iterable (.map()) without manually creating and joining individual Thread objects — it's the modern, higher-level, generally preferred way to work with threads for most use cases.
.submit() returns a Future object immediately, representing work that may not be complete yet — you can check its status, add a callback, or call.result() to block until it's done, making it easy to launch several tasks and collect their results as they complete.
Example
from concurrent.futures import ThreadPoolExecutor, as_completed import time def fetch_data(item_id): time.sleep(1) # simulate an I/O-bound operation return f"Data for {item_id}" with ThreadPoolExecutor(max_workers=3) as executor: futures = [executor.submit(fetch_data, i) for i in range(5)] for future in as_completed(futures): # process results as they finish print(future.result())
💡 ThreadPoolExecutor is generally the recommended modern approach over manually managing raw Thread objects for most real-world tasks — mentioning this preference directly signals current, idiomatic Python knowledge.
How do you use concurrent.futures.ProcessPoolExecutor?
Answer
ProcessPoolExecutor has the exact same interface as ThreadPoolExecutor (.submit(),.map(), as_completed()), but distributes work across separate processes instead of threads — making it the go-to highlevel tool for CPU-bound parallelism, sidestepping the GIL.
Because the two executor classes share an identical interface, you can often switch between them by changing just the import and class name, based on whether your workload is CPU-bound (ProcessPoolExecutor) or I/Obound (ThreadPoolExecutor) — a clean illustration of good API design.
Example
from concurrent.futures import ProcessPoolExecutor import time def cpu_bound_task(n): return sum(i * i for i in range(n)) if __name__ == "__main__": start = time.perf_counter() with ProcessPoolExecutor(max_workers=4) as executor: results = list(executor.map(cpu_bound_task, [10_000_000] * 4)) print(f"ProcessPoolExecutor: {time.perf_counter() - start:.2f}s") # Genuine speedup from true parallelism, unlike the ThreadPoolExecutor equivalent
💡 Pointing out that ThreadPoolExecutor and ProcessPoolExecutor share an identical interface — so switching between them is often a one-line change — demonstrates that you understand these are interchangeable tools for different workload types, not fundamentally different programming models.
What is asynchronous programming, and how does it differ from multithreading?
Answer
Asynchronous programming (via asyncio) achieves concurrency using a single thread and an event loop that switches between tasks whenever one is waiting (typically on I/O), rather than using multiple OS-level threads. It avoids both the GIL contention concerns of threading and the memory overhead of multiprocessing, but requires structuring code around async / await.
The key difference is cooperative versus preemptive multitasking: with threads, the OS can pause a thread at almost any point; with asyncio, a task voluntarily yields control (at an await point) rather than being interrupted — meaning a single async task that never awaits can block the entire event loop.
Example
import asyncio async def fetch_data(name, delay): print(f"Starting {name}") await asyncio.sleep(delay) # yields control back to the event loop while "waiting" print(f"Finished {name}") return f"Result from {name}" async def main(): results = await asyncio.gather( fetch_data("A", 2), fetch_data("B", 1), fetch_data("C", 3), ) print(results) asyncio.run(main()) # All three "fetches" run concurrently on a SINGLE thread, total time ~3s, not 6s
💡 The phrase "cooperative multitasking on a single thread" versus "preemptive multitasking across multiple OS threads" is the precise technical distinction interviewers are checking for — much more specific than a vague "async is different from threading."
What are async and await, and how do they work?
Answer
async def defines a coroutine function — calling it doesn't run the function immediately, it returns a coroutine object (similar to how calling a generator function returns a generator,. await pauses the current coroutine until the awaited operation completes, yielding control back to the event loop in the meantime.
You can only use await inside an async def function, and you can only meaningfully await an "awaitable" object — another coroutine, a Task, or a Future. Forgetting to await a coroutine call is a very common bug: the coroutine object is created but never actually runs.
Example
import asyncio async def greet(name): await asyncio.sleep(1) return f"Hello, {name}!" async def main(): # Correct: awaited, actually runs and returns a result result = await greet("Ana") print(result) # Bug: NOT awaited -- creates a coroutine object but never runs it! unused = greet("Ben") print(unused) # <coroutine object greet at 0x...> -- a RuntimeWarning is also printed asyncio.run(main())
What is an event loop in asyncio?
Answer
The event loop is the core scheduler that manages and runs all coroutines, deciding which one to resume when a previously awaited operation completes. asyncio.run(main()) creates the event loop, runs main() to completion, and then closes the loop — this is the standard, modern entry point for running async code.
Under the hood, the event loop continuously monitors pending I/O operations (network sockets, timers) and, as each one completes, resumes exactly the coroutine that was waiting on it — this is the actual mechanism that makes cooperative concurrency on a single thread possible.
Example
import asyncio async def task(name, delay): print(f"{name} started") await asyncio.sleep(delay) print(f"{name} finished") async def main(): await asyncio.gather(task("A", 1), task("B", 2)) asyncio.run(main()) # creates the event loop, runs main() to completion, then closes it # You rarely need to manage the event loop manually in modern asyncio code -- # asyncio.run() is the standard, recommended top-level entry point.
💡 Mentioning that asyncio.run() is the modern recommended entry point (replacing older, more manual patterns like loop = asyncio.get_event_loop()) signals current, up-to-date async knowledge rather than outdated tutorials.
What are coroutines, and how do they differ from regular functions and generators?
Answer
A coroutine (created by calling an async def function) is a special kind of resumable function, conceptually similar to a generator — both can pause and resume execution — but coroutines are specifically designed to be driven by an event loop via await, rather than manually via next().
Historically, Python's asyncio was actually built directly on top of generators (using yield from before native async / await syntax was introduced in Python 3.5) — understanding this lineage explains why coroutines and generators share so much conceptual DNA.
Example
import asyncio # A regular function: runs to completion immediately, once called def regular_function(): return "done immediately" # A generator: pauses at yield, resumed manually via next() def generator_function(): yield "first" yield "second" # A coroutine: pauses at await, resumed automatically by the event loop async def coroutine_function(): await asyncio.sleep(1) return "done after waiting" print(regular_function()) # "done immediately" -- runs right away print(next(generator_function())) # "first" -- driven manually by next() print(coroutine_function()) # <coroutine object ...> -- must be awaited/run to execute
💡 Mentioning that asyncio historically evolved from generator-based coroutines (yield from) before dedicated async / await syntax arrived in 3.5 is a great piece of "connects the history to the current design" context that shows depth.
How do you run multiple async tasks concurrently?
Answer
Use asyncio.gather(*coroutines) to run several coroutines concurrently and collect all their results once every one of them completes, or asyncio.create_task() to schedule a coroutine to start running in the background immediately, without necessarily waiting for it right away.
A very common mistake is await ing coroutines one at a time in sequence (await task1(); await task2()), which runs them sequentially, not concurrently — completely defeating the purpose of using asyncio in the first place. gather() is what actually launches them all at (logically) the same time.
Example
import asyncio async def fetch(name, delay): await asyncio.sleep(delay) return f"{name} done" async def sequential_wrong(): # BUG: this runs one after another, not concurrently! r1 = await fetch("A", 1) r2 = await fetch("B", 1) return [r1, r2] # takes ~2 seconds total async def concurrent_correct(): # CORRECT: runs both at once r1, r2 = await asyncio.gather(fetch("A", 1), fetch("B", 1)) return [r1, r2] # takes ~1 second total asyncio.run(concurrent_correct())
What is the difference between concurrency and parallelism?
Answer
Concurrency is about managing multiple tasks that are in progress at overlapping times (they may take turns, not necessarily execute at the exact same instant). Parallelism is about tasks actually executing simultaneously, typically requiring multiple CPU cores. asyncio and threading provide concurrency; multiprocessing (and multi-core CPU-bound work) provides genuine parallelism.
A helpful mental model: a single chef juggling three dishes on one stove, switching attention between them, is concurrency. Three chefs each cooking their own dish on separate stoves at the same time is parallelism. Python's GIL is precisely why threading gives you concurrency for CPU-bound work but not parallelism, while multiprocessing gives you both.
Example
# Concurrency (asyncio) -- one thread, tasks take turns via await # Concurrency (threading, I/O-bound) -- multiple threads, but GIL means only # one runs Python bytecode at any given instant; I/O waits overlap though # Parallelism (multiprocessing) -- multiple processes, genuinely simultaneous # execution across CPU cores # This distinction is exactly why: # - asyncio/threading suit I/O-bound work (waiting overlaps -- concurrency is enough) # - multiprocessing suits CPU-bound work (need actual simultaneous execution)
💡 The "one chef juggling dishes vs. multiple chefs on separate stoves" analogy is memorable and immediately makes the abstract distinction concrete — use a similar analogy rather than a purely technical definition.
What is the difference between CPU-bound and I/O-bound workloads?
Answer
A CPU-bound workload is limited by processor speed — it spends nearly all its time actively computing (numerical calculations, data processing, image manipulation). An I/O-bound workload is limited by waiting for external operations (network requests, disk reads, database queries) — the CPU is mostly idle, just waiting.
This distinction is the single most important factor in choosing a concurrency approach correctly (Q253): CPU-bound work needs genuine parallelism (multiprocessing) to speed up, while I/O-bound work benefits enormously from concurrency alone (threading or asyncio), since most of the "waiting" time can overlap across tasks.
Example
import time def cpu_bound_example(): # spends time computing -- CPU-bound return sum(i * i for i in range(50_000_000)) def io_bound_example(): # spends time waiting -- I/O-bound time.sleep(2) # simulates a network call or disk read return "data retrieved" # A quick diagnostic: if adding more threads doesn't meaningfully speed up # the work, and CPU usage is already near 100% on one core, it's CPU-bound. # If CPU usage stays low while the program "waits," it's I/O-bound.
💡 Offering a practical diagnostic — checking CPU utilization while the task runs — as a way to identify which category a real, unfamiliar workload falls into is more useful than just defining the two categories abstractly.
When would you choose threading vs. multiprocessing vs. asyncio?
Answer
Choose multiprocessing for CPU-bound work needing true parallelism. Choose threading for I/O-bound work, especially when integrating with existing synchronous/blocking libraries. Choose asyncio for I/O-bound work at very high concurrency (thousands of simultaneous connections), where thread-per-task overhead would be too costly, and when your I/O libraries support async natively.
asyncio scales to far more concurrent tasks than threading because coroutines are much cheaper than OS threads (no separate stack, less context-switching overhead) — but it requires your entire I/O stack (database drivers, HTTP clients) to be async-compatible to get the full benefit, whereas threading works with any existing blocking code without modification.
Example
def choose_concurrency_approach(workload_type, scale): if workload_type == "cpu_bound": return "multiprocessing" elif workload_type == "io_bound": if scale == "very_high" and "async_libraries_available": return "asyncio" # thousands of concurrent connections else: return "threading" # simpler, works with existing blocking libraries
💡 A senior-level answer explicitly mentions the "library compatibility" trade-off for asyncio — it's not automatically the best choice for I/O-bound work if your database driver or HTTP client library doesn't support async, since mixing sync and async carelessly causes real problems (Q254).
What are common pitfalls when mixing synchronous and asynchronous code?
Answer
Calling a blocking (synchronous) function directly inside an async def coroutine — without offloading it — blocks the entire event loop, freezing every other concurrent task, not just the one making the blocking call. This defeats the entire purpose of using asyncio.
The fix is to run blocking calls in a separate thread pool via asyncio.to_thread() (3.9+) or loop.run_in_executor(), so the blocking work happens off the event loop's single thread while other coroutines continue making progress normally.
Example
import asyncio import time def blocking_call(): # a synchronous, blocking function (e.g., old DB driver) time.sleep(2) return "blocking result" async def bad_example(): print("Before blocking call") result = blocking_call() # BLOCKS THE ENTIRE EVENT LOOP for 2 seconds! print("After blocking call") return result async def good_example(): print("Before blocking call") result = await asyncio.to_thread(blocking_call) # runs in a separate thread instead print("After blocking call") return result # During bad_example()'s blocking_call(), NO other coroutine can make any progress at all, # even ones with nothing to do with this specific task.
How would you scale a Python application to handle thousands of concurrent I/O operations?
Answer
Use asyncio with fully async-compatible libraries throughout the stack (an async web framework, an async database driver, an async HTTP client) — thousands of lightweight coroutines are far cheaper than thousands of OS threads, which would exhaust memory and context-switching capacity long before reaching that scale.
This question is really testing whether you understand why scale specifically pushes the decision toward asyncio over threading — each OS thread has meaningful memory overhead (typically megabytes for its stack) and the OS scheduler itself starts to struggle with context-switching overhead at very high thread counts, while coroutines are comparatively nearly free to create by the thousands.
Example
import asyncio import aiohttp # an async-compatible HTTP client, illustrative async def fetch(session, url): async with session.get(url) as response: return await response.text() async def fetch_all(urls): async with aiohttp.ClientSession() as session: tasks = [fetch(session, url) for url in urls] return await asyncio.gather(*tasks) # thousands of concurrent requests, one thread urls = [f"https://example.com/{i}" for i in range(5000)] # asyncio.run(fetch_all(urls)) # feasible with asyncio; would be impractical with 5000 threads
💡 Quantify the trade-off if you can — "an OS thread typically costs a few MB of stack space, so 5,000 threads could mean gigabytes of memory just for stacks, while 5,000 coroutines cost a tiny fraction of that" — concrete numbers make this answer far more convincing than a vague appeal to "efficiency."
Learn this topic
Recommended resourcesAffiliate links · may earn us a commission