Autocoder

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.

Level2 to 5 years
FocusGIL, threads, processes, asyncio
VersionCPython 3.10 and later

Decision table

State the workload first, then the tool. This single habit makes most concurrency answers sound senior.

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. 1

    What is the difference between a thread and a process?

    easy

    A 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. 2

    What is the GIL and why does it exist?

    medium

    The 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. 3

    When do threads speed up Python code and when do they not?

    medium

    Threads 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.

    python
    import 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))   # 1
  4. 4

    Show how to use multiprocessing for CPU-bound work.

    medium

    Use 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.

    python
    from 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. 5

    Predict the output: a race condition on a shared counter.

    hard

    count += 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.

    python
    import 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 it
  6. 6

    What synchronisation primitives does the threading module provide?

    medium

    Lock 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. 7

    What is a deadlock and how do you avoid it?

    medium

    A 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. 8

    Implement a producer-consumer with queue.Queue.

    medium

    Queue 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.

    python
    import 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. 9

    What is the difference between threading and asyncio?

    medium

    Threads 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.

    python
    import 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. 10

    What does join() do, and what is a daemon thread?

    medium

    t.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. 11

    How do processes share data in Python?

    hard

    Processes 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. 12

    What is the difference between fork and spawn start methods?

    medium

    fork 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. 13

    Why use concurrent.futures instead of raw threads?

    medium

    ThreadPoolExecutor 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.

    python
    from 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

See all in this section