Threads vs Processes
[!NOTE] This module explores the core principles of Threads vs Processes, deriving solutions from first principles and hardware constraints to build world-class, production-ready expertise.
1. The Heavyweight Process
Creating a process is expensive. It’s like building a new house for every guest.
- Isolation: Every process has its own address space.
- Communication: Requires IPC (Pipes, Sockets), which involves kernel intervention.
- Overhead:
fork()requires copying page tables. Context switching flushes the TLB (Translation Lookaside Buffer).
2. The Lightweight Thread
A thread is like a guest in the same house.
- Shared Memory: All threads in a process share the Heap, Code, and Global Variables.
- Private Memory: Each thread has its own Stack (for local variables) and Registers (Program Counter, Stack Pointer).
- Efficiency: Switching threads is faster because the memory mapping (TLB) stays valid.
3. Interactive: Memory Model Inspector
Visualize what is shared and what is private.
Process Address Space
Thread 1
Stack
Registers (PC)
Thread 2
Stack
Registers (PC)
Click a button to simulate memory access.
4. Threading Models
How does the OS manage threads?
- Kernel Threads (1:1): (Linux, Windows).
- Every user thread maps to 1 kernel thread.
- Pros: OS can schedule threads on different cores (True Parallelism).
- Cons: Creating a thread involves a syscall (Heavy).
- User Threads (N:1): (Old Java Green Threads).
- Many user threads map to 1 kernel thread.
- Pros: Fast switching (function call).
- Cons: If one blocks (I/O), the whole process blocks. No Multi-core.
- Hybrid / M:N: (Go Goroutines, Java Virtual Threads).
- M user threads run on N kernel threads.
- Best of both worlds. The runtime (JVM/Go Runtime) handles scheduling.
5. Code Example: Threading
Compare the syntax and the concept of “Virtual Threads” (Go/Java 21).
```java
public class VirtualThreads {
public static void main(String[] args) throws InterruptedException {
// Java 21+ Virtual Threads (M:N Model)
// Millions of these can run on a few OS threads.
Thread vThread = Thread.ofVirtual().start(() -> {
System.out.println("Running on a Virtual Thread: " + Thread.currentThread());
});
// Traditional Platform Thread (1:1 Model)
Thread pThread = new Thread(() -> {
System.out.println("Running on a Platform Thread: " + Thread.currentThread());
});
pThread.start();
vThread.join();
pThread.join();
}
}
```