Limited Offer

30% OFF Lifetime Access ($139) with code SYSTEM30

TOPIC #16Beginner 9 min read

Processes vs Threads

💡
Core Architecture Summary

Differentiate isolated memory address spaces from shared-memory lightweight execution units: Virtual memory, IPC, stack vs heap, and crash isolation.

Key Glossary Concepts in this TopicAll Glossary Terms

Process Address Space vs Multi-Threaded Memory Layout 🧬

Processes have independent virtual address spaces enforced by hardware MMUs; threads within a process share the heap, text, and data segments.

Process Address Space vs Multi-Threaded Memory Layout 🧬
100%
Rendering visual architecture flowchart...

01.1. What is an OS Process?

An Operating System Process is an independent execution container created by the OS kernel. Each process is allocated its own private Virtual Address Space mapped to physical RAM via the CPU Memory Management Unit (MMU) and OS page tables.

A process encapsulates:

  • Private Virtual Memory Map: Divided into Text (compiled code instructions), Data/BSS (globals/statics), Heap (dynamically allocated memory via malloc or garbage collectors), and Stack segments.
  • Kernel Resource Descriptors: File descriptor table (open files, active TCP sockets, pipes), environment variables, working directory, and user security credentials (UID/GID).
  • Hard Hardware Isolation: If Process A attempts to read or write to an address belonging to Process B without shared memory mappings, the CPU MMU generates a hardware page fault, triggering the OS to terminate Process A with a SIGSEGV (Segmentation Fault).

Creation Overhead: Spawning an OS process via fork() and exec() requires duplicating or copying page tables (using Copy-on-Write / CoW), allocating kernel control blocks (PCB), and initializing descriptors, typically taking 1 to 5 milliseconds and consuming megabytes of base memory.

02.2. What is a Thread?

A Thread (Lightweight Process or LWP) is the smallest unit of CPU execution schedulable by the OS kernel. Threads live inside an enclosing parent process.

Key Thread Characteristics:

  • Shared Memory: All threads inside the same process share the exact same Heap, global static variables, open file descriptors, and socket handles. Any thread can read or modify data created by any other thread in the process simply by dereferencing a memory pointer (0ns overhead).
  • Private State: Each thread maintains its own dedicated Stack (for local function variables and call frames), Program Counter (PC), and CPU register set.
  • The Crash Risk: Because memory is shared without hardware boundaries, if a single thread encounters an unhandled exception (e.g., dereferencing a null pointer in C++ or an unrecovered panic in Go), it corrupts the shared heap or crashes the entire parent process, taking down all sibling threads instantly.

03.3. Architectural Comparison: Multi-Process vs Multi-Threaded Models

Large-scale distributed systems choose between multi-process and multi-threaded architectures based on resilience vs memory efficiency:

Architectural QualityMulti-Process ArchitectureMulti-Threaded Architecture
Crash IsolationComplete: If Worker 1 crashes, Workers 2..N continue unaffected.None: A single thread segfault terminates the entire service.
Memory FootprintHigh: 20MB - 100MB+ per process (duplicate runtimes).Low: Few KB to MBs per thread (shared heap).
Data SharingSlow: Requires IPC (serialization, kernel context switches).Zero-Copy: Direct pointer access in shared heap.
Creation CostHeavy: 1 - 5 ms (fork() / exec()).Light: ~10 - 50 μs (pthread / clone).
Classic Real-World SystemsPostgreSQL, Chrome Browser, Nginx workers, Gunicorn.MySQL (InnoDB), Redis (I/O threads), Java Netty, Go services.

04.4. Inter-Process Communication (IPC) Mechanisms

When independent processes must collaborate, they use kernel-mediated IPC channels:

  1. Unix Domain Sockets (UDS): Bidirectional byte/datagram stream on the local filesystem. Bypasses the network TCP/IP stack (no checksums, no routing), achieving sub-microsecond latency. Used between Nginx and Gunicorn/Puma.
  2. Anonymous / Named Pipes (FIFOs): Unidirectional data streaming between parent-child or unrelated processes on the same host.
  3. Shared Memory (shm_open / mmap): Multiple processes map the same physical RAM pages into their virtual address spaces. Offers the highest possible IPC throughput (GB/s) because data transfers bypass the OS kernel completely, but requires explicit semaphore synchronization.
  4. Message Queues (POSIX / System V): Kernel-managed message queues for structured event passing.
python— Multi-process pool with IPC vs Multi-threaded execution in Python
import multiprocessing as mp
import threading

# Multi-threaded: Shares memory, but subject to GIL in Python
def thread_worker(shared_list, value):
    shared_list.append(value) # Direct shared memory mutation

# Multi-process: Total memory isolation, requires IPC Queue
def process_worker(ipc_queue, value):
    # Runs in completely separate OS process address space
    ipc_queue.put(value * 2) # Serialized and sent over OS pipe

⚖️Architectural Trade-offs & Production Realities

Architectural Advantages

  • Threads provide ultra-low memory overhead and zero-copy shared memory access across CPU cores.
  • Processes guarantee fault isolation: untrusted user code or memory leaks cannot corrupt other processes.
  • Multi-process architectures scale seamlessly across CPU sockets without global lock contention.

Trade-offs & Constraints

  • Threads require rigorous synchronization (mutexes, atomics) to prevent silent race conditions and data corruption.
  • Processes require complex serialization (JSON, Protobuf) and context-switching overhead for IPC.
  • A single thread crash kills the entire parent process, threatening service availability.
Production Implementation in Big Tech
PostgreSQL vs MySQL• Process-per-Connection vs Thread-per-Connection Architecture

PostgreSQL forks a dedicated OS process for every incoming database client connection, ensuring absolute memory protection and crash isolation. MySQL uses a single multi-threaded process, allocating a lightweight thread per connection to support thousands of concurrent client connections with significantly lower memory overhead.

🎯 Staff+ Engineering Takeaways

  • Processes are isolated by hardware MMU page tables; Threads share the process heap and file descriptors.
  • Threads maintain their own private stack and program counter.
  • A thread crash terminates the entire process; a process crash is isolated by the OS.
  • IPC (Unix Sockets, Pipes, Shared Memory) is required for inter-process data exchange.
  • Green threads (Goroutines) decouple concurrency from heavy OS thread stack overhead.

Topic Knowledge Assessment 🧠

Step through 2 scenario questions to test your staff-level grasp.

Question 1 of 20 answered
#1

What happens when two threads in the same process simultaneously write to the same global variable without synchronization primitives?

Rate This Architecture Chapter4.9 / 5.0 (38 ratings)

How clear and staff-actionable was this system breakdown?