Threads & Concurrency

threads versus processes

Think of an office. A process is a whole company with its own building - its own locked rooms, its own filing cabinets, its own front door. A thread is one employee inside that building. Two employees of the same company share all the rooms and cabinets freely; two people from different companies have to phone each other or mail documents to communicate. That picture captures the central difference: threads in one process share memory; separate processes do not.

More precisely: a process is a running program with its own private address space - its own view of memory, isolated by the operating system from every other process. A thread is a flow of execution inside a process, and every thread in a process shares that one address space: the same heap, the same global variables, the same code, the same open files. What each thread keeps to itself is small but vital - its own stack (for its local variables and call chain) and its own register state, including the program counter. So when thread A writes to a global variable or a heap object, thread B sees the change immediately, because they are looking at the same bytes. Two separate processes writing to 'the same' global each touch their own private copy and never collide.

Why this matters: sharing makes threads fast and convenient to communicate (just read and write shared memory) but dangerous (two threads can scribble on the same data and corrupt it - the whole subject of this field). Process isolation makes processes safe from each other (a crash or bad write in one cannot touch another's memory) but slower and more awkward to share data between (you need explicit inter-process communication). Choosing threads versus processes is choosing between cheap sharing with hazards, and strong isolation with overhead.

A web browser may run each tab as a separate process so one crashing page cannot take down the others - strong isolation. Inside a single tab, several threads (rendering, networking, scripting) share that tab's memory to cooperate quickly.

Processes for isolation, threads for cheap sharing - browsers use both deliberately.

Both threads in a process share the heap and globals, but each has its OWN stack - so a local variable in one thread is private. Passing a pointer to a local on thread A's stack to thread B is dangerous if A's function returns, because that stack frame is gone.

Also called
thread vs process執行緒與行程的差別