Skip to content
Concept ยท Software Development

Process vs Thread: The Difference, Measured in Python

Younus FardeenBy Younus FardeenUpdated 1 Dec 20269 min read
Short answer

A process is a running program with its own memory space. A thread is a unit of execution inside a process and shares that process's memory with its sibling threads. Processes are isolated and heavier to create and switch. Threads are lighter and share data, which makes them fast to coordinate and easy to corrupt without locks.

On this pageProcess vs thread: the short differenceContext switch: why threads are cheaper to switchMultithreading vs multiprocessing: measured in PythonShared memory and a race condition, with the fixInterview answers you can say out loudFrequently asked questions

This page is for students preparing for operating system rounds and for anyone who has written threading.Thread once and wondered why the code did not get faster. The definitions are in every textbook. What is harder to find is a measured comparison, so the demos below were run on 1 December 2026 with Python 3.9.6 on a 10-core Mac, and the timings quoted are the real output of one run.

If you are building toward a backend role, read this next to the backend developer roadmap and the system design interview guide, where the same ideas return as worker pools, queues and connection handling.

Process vs thread: the short difference

A process is the operating system's container for a running program: its own virtual address space, open files, and a process control block that the kernel uses to track it. A thread is a sequence of instructions scheduled inside a process. Every process has at least one thread. All threads of a process share the code, the heap and the global variables, but each thread has its own stack, program counter and registers.

Because memory is shared, two threads can pass data by reading the same variable, and two threads can also corrupt that variable by writing to it at the same time. Two processes cannot touch each other's memory by accident. To talk, they need explicit inter-process communication such as pipes, sockets or shared-memory segments.

PointProcessThread
MemoryOwn address spaceShares the process's heap, code and globals; own stack
Creation costHigher (new address space and kernel structures)Lower (reuses the existing address space)
CommunicationIPC: pipes, sockets, shared memory, message queuesPlain variables, queues in memory (needs synchronisation)
IsolationA crash usually stays inside that processA crash or memory bug can take down every thread in the process
Context switchHeavier: the CPU switches to a different address spaceLighter: same address space, only stack and registers change
Typical useSeparate programs, browser tabs or workers, CPU-heavy parallel jobsConcurrent I/O, background tasks, a server handling many clients
Python specificsmultiprocessing runs real parallel Python on many coresthreading runs concurrently but the GIL lets one thread run Python bytecode at a time

The thread row for Python is a Python-implementation detail, not an operating system rule. In Java or C++, two threads can run on two cores at the same moment. That difference is the whole point of the next section.

Context switch: why threads are cheaper to switch

A context switch is the kernel saving the state of the running task (registers, program counter, stack pointer) and loading the state of another. Switching between two threads of the same process keeps the same virtual-memory mapping. Switching between two processes also changes the address space, which invalidates cached address translations in the CPU and usually leaves the next task running on colder caches. That is the usual explanation for why a process switch costs more than a thread switch.

Be careful in interviews: do not quote microsecond numbers. They depend on the CPU, the operating system and what else is running, and any figure you memorise is probably from one blog post. Say what is switched and why one is heavier, and stop there.

Multithreading vs multiprocessing: measured in Python

The script below runs the same work three ways. The CPU-bound task is a plain loop of arithmetic. The I/O-bound task is time.sleep(0.5), which stands in for waiting on a network or disk. It prints the Python version and CPU count so you can compare your own machine.

import sys, time, threading, multiprocessing as mp

def cpu(n=6_000_000):
    total = 0
    for i in range(n):
        total += i * i
    return total

def io():
    time.sleep(0.5)          # stands in for a network or disk wait

def timed(label, fn):
    t = time.perf_counter(); fn(); print(f"{label:<34}{time.perf_counter() - t:5.2f} s")

def run_threads(fn, k=4):
    ts = [threading.Thread(target=fn) for _ in range(k)]
    for t in ts: t.start()
    for t in ts: t.join()

def run_procs(fn, k=4):
    ps = [mp.Process(target=fn) for _ in range(k)]
    for p in ps: p.start()
    for p in ps: p.join()

if __name__ == "__main__":
    print("Python", sys.version.split()[0], "| CPUs:", mp.cpu_count())
    timed("CPU-bound, 4 tasks in a loop", lambda: [cpu() for _ in range(4)])
    timed("CPU-bound, 4 threads", lambda: run_threads(cpu))
    timed("CPU-bound, 4 processes", lambda: run_procs(cpu))
    timed("I/O-bound, 4 waits in a loop", lambda: [io() for _ in range(4)])
    timed("I/O-bound, 4 threads", lambda: run_threads(io))

Output from one run on 1 December 2026 (timings change a little on every run):

Python 3.9.6 | CPUs: 10
CPU-bound, 4 tasks in a loop       1.14 s
CPU-bound, 4 threads               1.03 s
CPU-bound, 4 processes             0.39 s
I/O-bound, 4 waits in a loop       2.02 s
I/O-bound, 4 threads               0.51 s
CaseWhat happenedWhy
CPU-bound, threads1.03 s against 1.14 s in a loop: almost no gainThe global interpreter lock (GIL) lets only one thread execute Python bytecode at a time
CPU-bound, processes0.39 s: about 2.6 times faster than threads hereEach process has its own interpreter and its own GIL, so work runs on separate cores. Start-up cost is included in this figure, so short jobs gain less
I/O-bound, threads0.51 s against 2.02 s: about 4 times fasterA thread waiting in sleep or a socket call releases the GIL, so the four waits overlap

The rule that falls out: in CPython, use threads or asyncio for waiting (HTTP calls, database queries, file and socket I/O) and processes for computing (parsing, number crunching, image work). Since Python 3.13 there is an optional free-threaded build with the GIL disabled; the Python documentation notes that some third-party extension modules may not be ready for it, so check before relying on it. The demo above is the default GIL build.

The same trade-off decides how an API server is deployed: worker processes for parallelism, threads or async inside each worker for concurrent requests. See deploy a Python API for free for a small working example.

Shared memory and a race condition, with the fix

Because threads share variables, counter += 1 is not safe. It is really three steps: read the value, add one, write it back. If another thread writes between your read and your write, one increment is lost. This is a race condition. The demo below makes the thread switches very frequent with sys.setswitchinterval so the problem appears reliably; without it, short loops on a fast machine often get away with it, which is exactly why these bugs survive testing and appear in production.

import sys, threading

sys.setswitchinterval(1e-6)   # ask for very frequent thread switches so the race shows up quickly

counter = 0
def work(n, lock=None):
    global counter
    for _ in range(n):
        if lock:
            with lock:
                counter += 1
        else:
            tmp = counter          # read
            counter = tmp + 1      # write: another thread may have changed counter in between

def run(use_lock):
    global counter
    counter = 0
    lock = threading.Lock() if use_lock else None
    ts = [threading.Thread(target=work, args=(200_000, lock)) for _ in range(4)]
    for t in ts: t.start()
    for t in ts: t.join()
    return counter

if __name__ == "__main__":
    print("expected      :", 4 * 200_000)
    print("without a lock:", run(False))
    print("with a lock   :", run(True))

Output from one run (the unlocked total is different on every run, the locked total never is):

expected      : 800000
without a lock: 313134
with a lock   : 800000

A Lock makes the read-modify-write one indivisible step: only the thread holding the lock may run the code inside with lock:. The price is that the threads now take turns on that line, which is a real cost when many threads fight over one lock. Two locks taken in the wrong order bring a different problem, covered in deadlock in an operating system.

  • Prefer passing messages (queue.Queue) over sharing mutable variables.
  • Keep locked sections short and never call slow I/O while holding a lock.
  • Processes avoid this class of bug by default, because nothing is shared unless you share it on purpose.

Interview answers you can say out loud

QuestionA 30-second answer
Process vs thread?A process owns an address space and resources; threads are execution paths inside it that share that memory and have their own stack and registers. Processes are isolated and heavier; threads are lighter and share data, so they need synchronisation.
Why is a thread switch cheaper?Same address space, so the kernel only swaps registers and stack. A process switch also changes the address space, which hurts CPU caches and address-translation caches.
Multithreading vs multiprocessing?Multithreading gives concurrency inside one process and suits I/O-bound work. Multiprocessing gives true parallelism across cores with isolated memory and suits CPU-bound work. In CPython the GIL is why that split matters.
What is a race condition?A bug where the result depends on the timing of threads touching shared data. Fixed by a lock, an atomic operation, or by not sharing the data.
What does the GIL do?In standard CPython it allows one thread to run Python bytecode at a time, which protects the interpreter's internals. It does not make your own code thread-safe, as the counter demo shows.

For follow-ups about scheduling and memory, pair this page with Python interview questions. The same answers also appear in networking and systems rounds; see TCP vs UDP for how a server uses many connections at once.

Frequently asked questions

What is the main difference between a process and a thread?

A process has its own address space and resources, while threads live inside a process and share its memory, each with its own stack and registers. That makes processes isolated but heavier, and threads lighter but able to corrupt shared data without locks.

Is multithreading or multiprocessing faster in Python?

It depends on the work. For CPU-bound code, multiprocessing is faster because each process has its own GIL: in the demo above, 4 processes took 0.39 s against about 1.03 s for 4 threads. For I/O-bound code, threads are enough: four 0.5 s waits overlapped to 0.51 s.

What is a context switch in an operating system?

It is the kernel saving the state of one running task and loading another's, so many tasks share a CPU. A switch between processes also changes the address space, which is why it is usually costlier than a switch between threads of the same process.

Why do threads share memory but processes do not?

The operating system gives each process a separate virtual address space, so its memory is invisible to others. Threads are created inside one process and so use the same address space; only their stacks and registers are separate.

Does the GIL make Python threads safe?

No. The GIL protects the interpreter's internal state, but a statement like counter += 1 is several bytecode steps and threads can switch in between. The race condition demo loses updates even with the GIL, so you still need locks or queues.

Can one process have many threads and one thread have many processes?

A process can contain many threads. A thread belongs to exactly one process, so the reverse is not possible. A thread can start other processes, for example by launching a subprocess, but it does not own them.

Learn this with mentors

Programmes for builders and engineers with admissions open: live classes, mentors and project work.

Continue learning

Concept

Deadlock in OS

Four deadlock conditions, a runnable demo and Banker's algorithm in Python

6 min read
Roadmap

Backend developer roadmap

Pick a stack, then SQL, APIs, auth, queues and Docker, in order

5 min read
Interview prep

System design interview preparation

A 45-minute framework, core concepts, 10 classic problems and a 4-week plan

11 min read