Threads

Threads vs processes, what threads share, kernel vs user threads and threading models, thread pools, and green/virtual threads and coroutines.

Intermediate 4 min readLesson 4 of 16 Interview Q&A

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

Shared by all threads of a process
  • Code (text segment)
  • Heap and global data
  • Open files and sockets
  • Working directory, user ID
  • Signal handlers
Private to each thread
  • Stack (local variables, call frames)
  • Registers and program counter
  • Thread ID, scheduling state
  • Thread-local storage
  • Signal mask

Threads vs processes

ProcessesThreads
MemoryIsolated address spacesShared address space
Creation costHigher (new page tables, PCB)Lower (just a stack and a TCB)
Switching costHigher (address-space switch)Lower
CommunicationIPC: pipes, sockets, shared memoryJust read and write shared variables (carefully!)
Fault isolationA crash affects only that processA crash takes down every thread
ExamplesChrome tabs, PostgreSQL connections, gunicorn workersJava 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());
}

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.
ModelMappingExamples
1 : 1Each user thread is a kernel threadJava platform threads, pthreads, C# threads
N : 1Many user threads on one kernel threadEarly green threads; no parallelism
M : NMany user threads multiplexed onto a pool of kernel threadsGo 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.

submit(task)task queueboundedworker 1worker 2worker 3results

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.

Key takeaways
  • 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.
Interview questions
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).