Threads
Threads vs processes, what threads share, kernel vs user threads and threading models, thread pools, and green/virtual threads and coroutines.
A thread is a single sequence of execution within a process. A process starts with one thread and can create more; all of them share the process's memory and resources but each has its own stack and registers. Threads let one program do several things at once — serve many requests, keep a UI responsive while working, or use all CPU cores.
What threads share
- Code (text segment)
- Heap and global data
- Open files and sockets
- Working directory, user ID
- Signal handlers
- Stack (local variables, call frames)
- Registers and program counter
- Thread ID, scheduling state
- Thread-local storage
- Signal mask
Threads vs processes
| Processes | Threads | |
|---|---|---|
| Memory | Isolated address spaces | Shared address space |
| Creation cost | Higher (new page tables, PCB) | Lower (just a stack and a TCB) |
| Switching cost | Higher (address-space switch) | Lower |
| Communication | IPC: pipes, sockets, shared memory | Just read and write shared variables (carefully!) |
| Fault isolation | A crash affects only that process | A crash takes down every thread |
| Examples | Chrome tabs, PostgreSQL connections, gunicorn workers | Java servers, game engines, Node's libuv pool |
Creating threads
Thread t = new Thread(() -> System.out.println("hello from " + Thread.currentThread().getName()));
t.start();
t.join(); // wait for it to finish
// In practice: use an executor (thread pool)
try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
Future<Integer> f = pool.submit(() -> expensiveComputation());
System.out.println(f.get());
}import threading
from concurrent.futures import ThreadPoolExecutor
t = threading.Thread(target=lambda: print("hello"))
t.start()
t.join()
with ThreadPoolExecutor(max_workers=8) as pool:
results = list(pool.map(download, urls)) # good for I/O-bound work
# Note: the GIL lets only one thread run Python bytecode at a time.// Node.js: one JS thread + an event loop. For CPU work, use worker threads:
import { Worker } from "node:worker_threads";
const w = new Worker("./heavy.js", { workerData: { n: 40 } });
w.on("message", (result) => console.log(result));Kernel threads vs user threads
- Kernel (native) threads are scheduled by the OS. They run truly in parallel on multiple cores and blocking one doesn't block the others. Each costs a kernel structure and typically a 1–8 MB stack reservation, and switching goes through the kernel.
- User-level threads (green threads, fibers, coroutines) are managed by a runtime library inside the process. They're very cheap to create and switch, but the runtime has to avoid blocking the kernel thread underneath.
| Model | Mapping | Examples |
|---|---|---|
| 1 : 1 | Each user thread is a kernel thread | Java platform threads, pthreads, C# threads |
| N : 1 | Many user threads on one kernel thread | Early green threads; no parallelism |
| M : N | Many user threads multiplexed onto a pool of kernel threads | Go goroutines, Java virtual threads, Erlang processes, Tokio tasks |
M : N gives you millions of cheap concurrent tasks while still using every core. Go and Java 21+ make blocking calls inside them cheap by parking the lightweight thread and freeing the kernel thread. See Virtual threads.
Thread pools
Creating a thread per task is wasteful and unbounded (10,000 requests → 10,000 threads → memory exhaustion and thrashing). A thread pool keeps a fixed set of worker threads pulling tasks from a queue.
How many threads?
- CPU-bound work: about the number of cores.
- I/O-bound work: cores × (1 + wait time / compute time). A task that waits 90% of the time can use about 10 threads per core.
- Always bound the queue too, and decide what happens when it's full (reject, block the caller, or run in the caller) — that's backpressure.
Concurrency vs parallelism
- Concurrency — dealing with many things at once: tasks overlap in time, possibly interleaved on one core.
- Parallelism — doing many things at the same instant on multiple cores.
Node.js is highly concurrent (one thread juggling thousands of connections) but not parallel for JavaScript code. A multithreaded numeric program is both. More: Event loop, asyncio.
- Threads share the heap, code and files; each has its own stack and registers.
- Threads are cheaper than processes but give up isolation.
- Kernel threads give real parallelism; user/green threads are cheap; M:N combines both.
- Use thread pools with bounded queues; size by CPU vs I/O work.
- Concurrency is about structure; parallelism is about simultaneous execution.
QWhen would you use processes instead of threads?medium
When you need isolation (a crash or memory corruption shouldn't take down the rest), security boundaries (browser tabs), to get around a GIL (Python multiprocessing), or to scale across machines. Threads are better when tasks share lots of data and need cheap communication.
QWhy not create one OS thread per incoming request?medium
Each thread costs memory (stack) and scheduler overhead. At tens of thousands of concurrent requests you run out of memory or spend most of the time context-switching. Use a bounded pool, async I/O, or lightweight threads (virtual threads, goroutines).