AlgoPlusAlgoPlus
Learn/Operating Systems
Lesson

Process vs Thread

A process owns an address space; a thread runs inside it. Threads share memory — cheap to switch, but state must be synchronized.

8 min read Watch it move Build it

A process is a running program with its own private slice of memory — its address space, holding the program's code, its global data, and a heap it can grow. A thread is a single flow of execution *inside* a process. A process always has at least one thread; it can have many, and they all share the process's address space. That sharing is the whole trade-off: threads coordinate cheaply and switch fast, but because they share memory, that shared state must be carefully synchronized.

What each one owns

  1. 1The process owns the address space — code, global data, and heap — plus OS resources like open files and sockets. All its threads share these.
  2. 2Each thread owns its own stack (local variables and call history), its CPU registers, and its program counter (where it is in the code).
  3. 3Shared by every thread in a process: the heap and the globals — so one thread can see and change another's data directly.
Why thread switches are cheaper
Switching between two threads of the *same* process leaves the memory map (and the TLB) intact — only registers and the stack pointer change. Switching between *processes* must swap the whole address space and typically flush the TLB, which is heavier.

The cost of sharing — synchronization

Because threads share memory, an unlucky interleaving can corrupt it.

int counter = 0;          // global, shared by both threads

// two threads each run:
counter = counter + 1;    // read, add, write -- NOT atomic

// an interleaving that loses an update:
//   A reads 0        B reads 0
//   A writes 1       B writes 1   <- should be 2

Both threads share counter, so an unlucky overlap loses an update — a race condition, fixed with a lock or semaphore. Separate processes don't share memory by default, so they sidestep this; but to cooperate they must use inter-process communication (IPC) — pipes, sockets, or explicitly shared memory.

Rule of thumb
Reach for threads when tasks need to share lots of data quickly inside one program; reach for separate processes when isolation and fault-containment matter more than communication speed — a crash in one process can't corrupt another's memory.
OperationTimeSpace
Thread context switch · TLB stays warmfastshared address space
Process context switch · swap memory map, flush TLBslowerseparate address space
Check yourself
Two threads of the same process both run counter = counter + 1 with no lock. What is the risk?