Python Multithreading and Multiprocessing Interview Questions
Last updated 2026-11-19
Concurrency questions test whether you can choose the right tool for a job. In Python the answer depends on the GIL, so interviewers want to hear whether the work is CPU-bound or I/O-bound before you pick threads, processes or asyncio.
This page explains the trade-offs, the synchronisation primitives you are expected to know, and the classic race condition and deadlock puzzles. Code examples use the standard library only.
| Level | 2 to 5 years |
|---|---|
| Focus | GIL, threads, processes, asyncio |
| Version | CPython 3.10 and later |
Decision table
State the workload first, then the tool. This single habit makes most concurrency answers sound senior.
- I/O-bound with a few tasks: threading or ThreadPoolExecutor
- I/O-bound with thousands of connections: asyncio
- CPU-bound: multiprocessing or ProcessPoolExecutor
- Mixed: processes for compute, threads or async for I/O inside each
Further reading
Background on how the interpreter manages objects is in Python memory management. For process and thread theory independent of Python, see operating systems interview questions. Preparation advice is in how to crack a Python interview.
Python Multithreading and Multiprocessing Interview Questions: questions with worked answers
1 What is the difference between a thread and a process?
easyA process has its own memory space and the operating system schedules it independently. A thread lives inside a process and shares its memory with sibling threads, so communication is cheap but needs synchronisation. Processes are heavier to start and communicate through pipes, queues or shared memory, but they are isolated, so a crash in one does not affect others. In CPython each process has its own interpreter and GIL.
2 What is the GIL and why does it exist?
mediumThe Global Interpreter Lock lets one thread at a time execute Python bytecode in CPython. It exists because reference counting is not thread-safe, and one global lock is a simple, fast way to protect it. The interpreter forces a thread switch periodically, every five milliseconds by default, and also releases the lock around blocking I/O and in many C extensions such as NumPy. Recent versions offer an optional free-threaded build, but the standard build still has the GIL.
3 When do threads speed up Python code and when do they not?
mediumThreads speed up I/O-bound tasks such as network calls, because while one thread waits the lock is released and another runs. They do not speed up pure Python CPU-bound loops, which can even run slower because of switching. The test below shows I/O overlap: three one-second sleeps take about one second, not three.
pythonimport time from concurrent.futures import ThreadPoolExecutor t = time.perf_counter() with ThreadPoolExecutor(3) as ex: list(ex.map(lambda _: time.sleep(1), range(3))) print(round(time.perf_counter() - t)) # 14 Show how to use multiprocessing for CPU-bound work.
mediumUse a process pool so each worker has its own interpreter and GIL. Arguments and results are pickled, so functions must be defined at module level, and the entry point needs an if __name__ guard because spawn-based platforms re-import the module. Overhead makes it worthwhile only for tasks heavier than the cost of sending data.
pythonfrom concurrent.futures import ProcessPoolExecutor def square_sum(n): return sum(i * i for i in range(n)) if __name__ == "__main__": with ProcessPoolExecutor() as ex: print(list(ex.map(square_sum, [10**5, 2 * 10**5])))5 Predict the output: a race condition on a shared counter.
hardcount += 1 is not atomic: it loads, adds and stores in separate bytecodes, so two threads can read the same value and one update is lost. The final total may be below the expected value, and varies between runs. Protect the update with a threading.Lock, or avoid shared state by using a Queue or per-thread results.
pythonimport threading count = 0 lock = threading.Lock() def work(): global count for _ in range(100_000): with lock: count += 1 ts = [threading.Thread(target=work) for _ in range(4)] for t in ts: t.start() for t in ts: t.join() print(count) # 400000 with the lock; may be less without it6 What synchronisation primitives does the threading module provide?
mediumLock gives mutual exclusion. RLock can be re-acquired by the same thread. Semaphore limits how many threads enter a section, such as capping connections. Event lets one thread signal others. Condition supports wait and notify patterns. Barrier makes threads wait for each other. Queue, from the queue module, is the preferred way to pass work between threads since it is already thread-safe.
7 What is a deadlock and how do you avoid it?
mediumA deadlock happens when threads wait on each other forever, typically when thread A holds lock 1 and wants lock 2 while thread B holds lock 2 and wants lock 1. Avoid it by acquiring locks in one consistent global order, holding locks for as short a time as possible, using timeouts such as lock.acquire(timeout=1), and preferring message passing over shared state. The four Coffman conditions are covered in operating systems interview questions.
8 Implement a producer-consumer with queue.Queue.
mediumQueue handles the locking. Producers put items, consumers get them, and a sentinel value tells consumers to stop. task_done and join let the main thread wait until all items are processed. A bounded queue also gives back-pressure, since put blocks when the queue is full.
pythonimport queue, threading q = queue.Queue(maxsize=5) def producer(): for i in range(3): q.put(i) q.put(None) def consumer(): while (item := q.get()) is not None: print("got", item) t = threading.Thread(target=consumer); t.start() producer(); t.join()9 What is the difference between threading and asyncio?
mediumThreads are scheduled preemptively by the operating system, which can switch at almost any bytecode, so shared state needs locks. asyncio runs many coroutines on one thread with cooperative scheduling: switches happen only at await points, so there are fewer races and far lower per-task overhead, which suits thousands of network connections. The cost is that any blocking call stalls the entire event loop, and libraries must be async-aware.
pythonimport asyncio async def job(n): await asyncio.sleep(1) return n async def main(): print(await asyncio.gather(job(1), job(2), job(3))) # [1, 2, 3] in about 1s asyncio.run(main())10 What does join() do, and what is a daemon thread?
mediumt.join() blocks the caller until thread t finishes, optionally with a timeout. A daemon thread, created with daemon=True, does not prevent the program from exiting: when only daemon threads remain, the interpreter exits and kills them abruptly, so they are unsuitable for work that must finish or clean up, but fine for background monitoring.
11 How do processes share data in Python?
hardProcesses do not share memory by default. Options are multiprocessing.Queue and Pipe, which pickle objects between processes, multiprocessing.Value and Array for small shared C-type data, shared_memory for large buffers, and Manager objects that proxy lists and dicts through a server process, which is convenient but slower. Prefer passing messages over sharing mutable state.
12 What is the difference between fork and spawn start methods?
mediumfork copies the parent process, which is fast but can copy locks and threads in an inconsistent state, and is unavailable on Windows. spawn starts a fresh interpreter and imports the main module again, which is slower but safer, and the default on Windows and macOS. Linux used fork historically, and recent versions are moving the default away from it. That is why top-level code must sit under the main guard.
13 Why use concurrent.futures instead of raw threads?
mediumThreadPoolExecutor and ProcessPoolExecutor offer one interface with submit, map and Future objects. Futures carry results and exceptions back to the caller, as_completed yields results in completion order, and the context manager shuts down cleanly. This removes manual thread bookkeeping and makes it trivial to switch between threads and processes when requirements change.
pythonfrom concurrent.futures import ThreadPoolExecutor, as_completed with ThreadPoolExecutor(2) as ex: futs = [ex.submit(pow, 2, n) for n in (3, 4)] print(sorted(f.result() for f in as_completed(futs))) # [8, 16]
Frequently asked questions
Is Python multithreading useless because of the GIL?
No. It is useful for I/O-bound work, and many C extensions release the GIL for heavy computation. It is not useful for CPU-bound pure Python code.
Which is faster, multiprocessing or multithreading?
For CPU-bound pure Python, multiprocessing. For I/O-bound work, threads or asyncio, which have much lower start-up and memory costs.
Is the Python queue module thread-safe?
Yes. queue.Queue handles its own locking. A plain list or deque is not a substitute for coordinated producer-consumer logic.
What is the difference between concurrency and parallelism?
Concurrency is structuring a program to make progress on several tasks, possibly interleaved on one core. Parallelism is running tasks at the same instant on multiple cores.
Related guides
More in Programming Language Interview Questions by Language
- Python OOPs Interview Questions
- Python String Interview Questions
- SQL CTE and Recursive Query Interview Questions
- SQL GROUP BY and HAVING Interview Questions
- SQL Indexes Interview Questions
- SQL Interview Questions and Answers
- SQL Interview Questions for Freshers
- SQL Joins Interview Questions
- SQL Query Practice: Interview Questions with Solutions
- SQL Subqueries Interview Questions
- SQL Window Functions Interview Questions
- TypeScript Interview Questions and Answers