🐍 Python for Everyone

← Back to challenges

Chapter 20 Interview Prep 45 min read

Interview Questions: Multithreading

The GIL and race conditions are two of the most commonly asked Python interview topics, because they test whether a candidate actually understands what threading does and doesn't help with, rather than just knowing the syntax. This set covers threading.Thread/.start()/.join(), I/O-bound vs. CPU-bound work, the GIL's real behavior, race conditions and why they're hard to catch, threading.Lock, thread safety patterns, and concurrent.futures.ThreadPoolExecutor.

1 Does Python's threading module give a program true parallelism?

Not for CPU-bound work, and that distinction is the crux of this question. The GIL (Global Interpreter Lock) allows only one thread to execute Python bytecode at a time, even on a multi-core machine, so two threads never run Python code simultaneously on separate cores. What threading genuinely does provide is concurrency for I/O-bound work: a thread waiting on a network response, disk read, or time.sleep() releases the GIL during that wait, letting another thread make real progress. So the honest answer is "it depends on the kind of work" — true parallel execution of Python code needs multiprocessing (separate processes, each with its own interpreter and GIL) or specialized libraries, not threading.

Answering with a flat "yes" (ignoring the GIL entirely) or a flat "no, threading is pointless in Python" (ignoring that it genuinely helps I/O-bound work).

"If a program needs to genuinely max out 8 CPU cores computing something, is threading or multiprocessing the better tool?" (multiprocessing — each process gets its own interpreter and its own GIL, so 8 processes can actually use 8 cores simultaneously; 8 threads cannot, since they all share one GIL.)

2 What is the difference between I/O-bound and CPU-bound work, and why does it matter for choosing whether to use threading?

I/O-bound work spends most of its time waiting on something outside the CPU — a network response, a disk read, a database query — the CPU is idle during that wait. CPU-bound work spends most of its time actually computing, with the CPU busy continuously and nothing to wait on. It matters because threading's entire benefit comes from overlapping waits: a thread waiting on I/O releases the GIL, letting other threads run during that idle time. A CPU-bound thread almost never releases the GIL, so adding more threads to CPU-bound work doesn't meaningfully speed anything up — it can even slow things down slightly, from the overhead of switching between threads that all still have to take turns on one CPU core's worth of GIL access.

Reaching for threading to speed up a pure computation, or not being able to give a concrete example of each category.

"Is calculating the ten-millionth prime number I/O-bound or CPU-bound?" (CPU-bound — it's pure computation with nothing to wait on, so threading wouldn't meaningfully speed it up in standard Python.)

3 Walk through what threading.Thread(target=fn, args=(...)), .start(), and .join() each do.

threading.Thread(target=fn, args=(...)) creates a thread object configured to run fn with the given arguments, but doesn't start it running yet. .start() actually begins running the thread, immediately returning control to the calling code rather than waiting for the thread to finish — calling .start() on several threads in a row is what lets their work begin overlapping. .join() pauses the calling code until that specific thread has completely finished. The common pattern is: create every thread, call .start() on every one in a first loop, then call .join() on every one in a separate second loop — calling .join() immediately after each .start() inside the same loop iteration would make every thread finish before the next one even begins, removing all concurrency.

Calling .join() immediately after .start() for each thread inside one loop (accidentally serializing everything), or not knowing that Thread() alone doesn't start anything.

"If code creates 5 threads, calls .start() and then immediately .join() on each one inside the same loop iteration, is that actually concurrent?" (No — each thread fully finishes (via .join()) before the next one is even created and started, so the 5 threads run one after another, exactly like ordinary sequential code, just with unnecessary thread overhead added.)

4 What is the GIL, and why does CPython have it?

The Global Interpreter Lock is a lock built into the standard Python interpreter (CPython) that allows only one thread to execute Python bytecode at any given instant, regardless of how many CPU cores the machine has. It exists primarily to keep CPython's internal memory management (specifically, reference counting for garbage collection) simple and safe by default, without needing much more fine-grained locking scattered throughout the interpreter's internals. The tradeoff is exactly what makes this a common interview question: it simplifies the interpreter's implementation at the cost of true parallel execution of Python bytecode across threads.

Not knowing what the GIL protects (reference counting / internal interpreter state) or claiming it's an arbitrary, purposeless limitation.

"Is the GIL a feature of the Python language itself, or specific to one implementation?" (Specific to CPython, the standard/reference implementation most people mean by "Python" — other implementations, like Jython or the experimental free-threaded CPython builds, handle this differently.)

5 If the GIL only lets one thread run Python code at a time, why does threading still speed up I/O-bound programs at all?

Because a thread that's genuinely waiting on I/O — a network call, a disk read, time.sleep() — isn't executing any Python bytecode during that wait at all, so it releases the GIL for the duration. That's the exact moment another thread can pick up the GIL and make real progress. The result: multiple I/O-bound waits can genuinely overlap in wall-clock time, even though, at the level of "which thread is executing bytecode right now," it's always exactly one thread or none. This is the single most important nuance to get right about the GIL — it restricts bytecode execution, not waiting.

Concluding "the GIL means threading is useless" without distinguishing bytecode execution from waiting, which throws away the entire I/O-bound use case.

"During a time.sleep(2) call inside a thread, is that thread holding the GIL for the full 2 seconds?" (No — it releases the GIL for the duration of the sleep, specifically so other threads can run during that otherwise-wasted time.)

6 What is a race condition, and what two conditions need to be true for one to happen?

A race condition is a bug where a program's correctness depends on the unpredictable timing/order in which multiple threads happen to run. Two things need to be true simultaneously: the state has to be shared (more than one thread can see and touch it), and it has to be mutated (at least one thread writes to it, not just reads it) — multiple threads only reading shared state, with nobody writing, is perfectly safe with no lock needed. When both are true and there's no coordination between the threads (no lock, no shared-nothing design), the outcome depends on exactly how the threads happen to interleave, which can differ from run to run.

Saying any shared state is automatically risky (read-only sharing is fine) or not being able to name both required conditions (shared AND mutated).

"If five threads all only read the same shared dict, with nobody ever writing to it, is a lock needed?" (No — read-only access from multiple threads, with no writer, has nothing to race on; a lock is needed specifically when at least one thread writes while others read or write the same state.)

7 Why can something as simple-looking as counter += 1 cause a race condition?

Because it isn't actually one atomic step under the hood — it's three: read the current value of counter, add 1 to it, and write the new value back. If a thread reads counter, gets paused before writing back (the GIL can switch to another thread between these steps), and a second thread reads the same still-old value and writes its own update, the first thread's eventual write can overwrite the second thread's work entirely — one whole increment is silently lost. This is exactly why "this line looks simple" is not the same question as "is this line safe to run from multiple threads" — the safety question is about how many underlying steps an operation actually takes, not how it looks in source code.

Assuming any single line of Python source code is automatically one atomic operation from the interpreter's point of view.

"If 4 threads each run counter += 1 exactly 1000 times with no lock, will the final value of counter always be exactly 4000?" (Not reliably — it's very likely to be 4000 or close to it much of the time in practice, but it is not guaranteed, and a correct answer should never depend on something that isn't guaranteed; a lock is what actually guarantees the correct total every time.)

8 How does threading.Lock actually fix a race condition?

A lock lets only one thread execute the code inside a protected block at a time — any other thread that reaches with lock: while the lock is already held simply waits until it's released. Wrapping the exact read-modify-write sequence that caused the race (reading the shared value, computing a new value, writing it back) inside with lock: closes the interleaving gap entirely: no other thread can start its own read-modify-write sequence on that same state until the current thread's is completely finished and the lock is released. with lock: is preferred over manual lock.acquire()/lock.release() because it automatically releases the lock even if an exception happens inside the block, avoiding a permanently-stuck lock.

Believing a lock makes code run faster (it doesn't — it trades some concurrency for correctness) or using manual acquire()/release() without a try/finally, risking a lock that never gets released if an exception is raised.

"Does adding a lock make threaded code run faster?" (No — it makes it correct when shared mutable state is involved, at the cost of some threads occasionally having to wait their turn; the actual code, once inside the lock, still runs on one thread at a time, same as without threading at all.)

9 How much code should be inside a lock's protected block?

Only the minimum code that actually touches the shared mutable state being protected — not more. Every line inside a lock's block forces every other thread wanting that lock to wait, so locking more than necessary (an entire function's body, for instance, when only one shared counter update inside it actually needs protecting) needlessly serializes work that could otherwise run concurrently, undermining much of threading's benefit. The habit to build: identify exactly which read-modify-write sequence touches shared state, and scope with lock: as tightly as possible around just that.

Wrapping an entire function (including I/O waits, unrelated computation, or anything not touching the shared state) inside a lock "just to be safe."

"If a function does a slow time.sleep() call and then a quick shared-counter update, should the lock wrap the sleep too?" (No — only the counter update needs the lock; wrapping the sleep as well would make every other thread wait for that entire sleep before it can even attempt its own update, needlessly serializing the slow part of the work.)

10 What's the alternative to using a lock, and when is it preferable?

The alternative is avoiding shared mutable state between threads entirely — giving each thread its own independent local data to work with, and only combining results together after every thread has finished (after every .join()). This "shared-nothing" pattern is preferable whenever the actual work naturally splits into independent pieces that don't need to see each other's progress mid-execution — it's simpler to reason about and faster, since there's nothing to protect and nothing for threads to wait on each other for. A lock becomes the necessary tool specifically when threads genuinely need to read and update the same piece of state as they go, not just contribute to a final combined result at the end.

Reaching for a lock by default even when the work could easily be restructured to avoid sharing state at all, or not recognizing when shared state actually is unavoidable.

"If 4 threads each need to compute an independent partial sum and the only thing that matters is their combined total at the very end, does the combining step itself need a lock?" (Not if each thread computes its own local partial sum and only appends it to a shared list once, at the very end — a single append per thread, after all computation is done, avoids the read-modify-write pattern that actually causes race conditions.)

11 What does threading.local() do?

It creates a special object where each thread automatically sees its own separate, private copy of whatever attributes are stored on it. If Thread A sets data.value = 1 and Thread B sets data.value = 2 on the exact same threading.local() object, they never collide or overwrite each other — each thread is silently reading and writing its own private storage behind the same shared name. It's most useful when a shared object genuinely needs to exist across a library or framework's code, but different threads should each keep their own version of specific values on it, without every piece of code that touches it needing to manually thread the right per-thread value through as a parameter.

Confusing threading.local() with a lock (it's not a synchronization primitive at all — it sidesteps sharing rather than protecting it) or assuming it automatically makes any object thread-safe.

"Does threading.local() remove the need for a lock elsewhere in the same program?" (Only for the specific attributes stored on that particular threading.local() object — any other genuinely shared, mutated state elsewhere in the program still needs its own protection, either a lock or a shared-nothing design.)

12 What does concurrent.futures.ThreadPoolExecutor offer over creating raw Thread objects directly?

It manages a fixed, reusable pool of worker threads automatically, removing the need to manually create, start, and join every individual Thread object, and removing the need to manually collect results into a shared list (a raw Thread's target function has no built-in way to hand a return value back). .map(fn, items) runs fn across every item concurrently and returns results in the same order as the input, regardless of which one actually finished first. .submit(fn, *args) plus as_completed() is the alternative for when a program wants to react to each result as soon as it's ready, in completion order rather than submission order. It's the higher-level, more commonly reached-for tool in real-world threaded code specifically because it removes most of the manual bookkeeping raw Thread objects require.

Not knowing the difference between .map() (ordered) and .submit()/as_completed() (completion order), or believing a thread pool makes shared mutable state automatically safe.

"Does using a ThreadPoolExecutor remove the need for a lock if the submitted work reads and writes the same shared counter?" (No — a thread pool changes how threads are created and managed, not whether shared mutable state needs protecting; the exact same lock or shared-nothing pattern is still required.)

13 Why are race conditions considered especially dangerous or hard-to-catch bugs in production code?

Because their symptoms depend on precise, unpredictable timing between threads rather than on the input data alone. Code with a race condition can pass every test run during development — if the specific bad interleaving simply doesn't happen to occur during those particular runs — and then fail unpredictably in production, often only under real concurrent load or heavier traffic than any test environment produces. This makes "it passed my tests" much weaker evidence of correctness for threaded code sharing mutable state than it is for ordinary sequential code, and it's exactly why defensive habits (locking shared mutable state, or avoiding sharing it at all) have to be reasoned about directly rather than verified by testing alone.

Treating a threaded program that "passed all tests" as proven correct with respect to race conditions, without separately reasoning about which state is shared and mutated.

"If a race condition exists in some code but happens to not manifest during 100 test runs, does that mean the code is safe?" (No — it means the bad interleaving simply didn't occur during those particular 100 runs; the underlying unsafe pattern (shared, mutated state with no lock) is still there and can still fail under different timing, load, or hardware.)

14 Give three real-world examples of tasks well-suited to threading, and explain what they have in common.

Concurrent file downloads (pulling several files from a server, or several servers, at once instead of one at a time), concurrent API calls (checking several external services' responses at once, like weather for five cities, instead of sequentially), and parallel file processing (reading and processing several independent files, where each one spends real time waiting on disk I/O). What they all have in common: every one is I/O-bound — the actual work is mostly waiting on something outside the CPU, not computing — which is exactly the category threading speeds up by letting those waits overlap instead of happening one after another. None of them would benefit meaningfully if the "work" were pure computation instead of waiting.

Naming a CPU-bound example (image processing's actual pixel math, heavy numerical computation) as a good threading use case without qualifying that the I/O part (reading the file, not processing it) is the piece that actually benefits.

"Would resizing 1,000 images in memory (pure CPU-bound pixel computation, no file I/O) benefit meaningfully from Python threading?" (Not meaningfully — that's CPU-bound work with almost nothing to wait on, so threads would mostly take turns on the GIL rather than genuinely overlapping; multiprocessing would be the better fit for that specific case.)

Rapid-Fire Review

Quick recall check — fill in each blank and hit Check.

🎉 Perfect score — you're ready to talk about this chapter in an interview.
← Challenges Build the Project →