Threads & Concurrency Models
Threads vs processes, what threads share, user vs kernel threads and threading models, thread pools, the GIL, green threads, coroutines and event loops, and concurrency vs parallelism.
Why threads?
A thread is an independent flow of execution within a process. All threads of a process share its memory, so they can cooperate on the same data without copying.
Reasons to use multiple threads:
- Responsiveness — keep a UI or server responsive while work happens in the background.
- Parallelism — use multiple CPU cores for one task.
- Overlapping I/O with computation — one thread waits for disk/network while another computes.
- Cheaper than processes — creation and switching avoid copying address spaces.
Process vs thread
| Process | Thread | |
|---|---|---|
| Address space | own | shared with siblings |
| Creation cost | high (fork, page tables) | lower (clone with shared VM) |
| Context switch | higher (address space + TLB) | lower |
| Communication | IPC (pipes, sockets, shm) | shared memory directly |
| Fault isolation | crash affects only itself | crash kills all threads |
| Synchronization needed | rarely | always for shared mutable data |
Creating threads
#include <pthread.h>
#include <stdio.h>
void *worker(void *arg) {
int id = *(int *)arg;
printf("hello from thread %d\n", id);
return NULL;
}
int main(void) {
pthread_t t[4];
int ids[4];
for (int i = 0; i < 4; i++) {
ids[i] = i;
pthread_create(&t[i], NULL, worker, &ids[i]);
}
for (int i = 0; i < 4; i++) pthread_join(t[i], NULL); // wait for all
return 0;
}
import threading
def worker(i):
print(f"hello from thread {i}")
threads = [threading.Thread(target=worker, args=(i,)) for i in range(4)]
for t in threads:
t.start()
for t in threads:
t.join()
// Java 21+: virtual threads are cheap enough to create one per task
try (var executor = java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 4; i++) {
int id = i;
executor.submit(() -> System.out.println("hello from " + id));
}
} // close() waits for all tasks
Threading models
| Model | Mapping | Examples | Pros | Cons |
|---|---|---|---|---|
| N:1 | many user threads → 1 kernel thread | early Java green threads, GNU Pth | very cheap switches | no parallelism; one blocking call blocks all |
| 1:1 | each user thread = kernel thread | Linux pthreads (NPTL), Windows, Java platform threads | real parallelism; simple | heavier (syscalls to create, ~8 MB stack reservation) |
| M:N | M user threads on N kernel threads | Go, Java virtual threads, Erlang, Tokio tasks | cheap + parallel | complex runtime; must avoid blocking carriers |
Thread pools
Creating a thread per task is wasteful and unbounded. A thread pool keeps a fixed set of workers pulling tasks from a queue.
from concurrent.futures import ThreadPoolExecutor
import urllib.request
urls = ["https://example.com"] * 20
def fetch(url):
with urllib.request.urlopen(url, timeout=5) as r:
return len(r.read())
with ThreadPoolExecutor(max_workers=8) as pool:
sizes = list(pool.map(fetch, urls))
ExecutorService pool = new ThreadPoolExecutor(
8, 8, // core and max threads
0L, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<>(1000), // BOUNDED queue = backpressure
new ThreadPoolExecutor.CallerRunsPolicy()); // when full, slow the producer down
Sizing
- CPU-bound: ≈ number of cores.
- I/O-bound:
cores × (1 + wait/compute), capped by downstream limits (DB pool size). - Always bound the queue. An unbounded queue turns overload into out-of-memory and unbounded latency.
The event-loop model
Instead of one thread per connection, one thread multiplexes many non-blocking sockets using epoll/kqueue:
import asyncio
async def handle(reader, writer):
while data := await reader.read(1024): # suspends; loop serves others meanwhile
writer.write(data) # echo
await writer.drain()
writer.close()
async def main():
server = await asyncio.start_server(handle, "0.0.0.0", 8080)
async with server:
await server.serve_forever()
asyncio.run(main())
| Model | Memory per connection | Blocking a handler | Multi-core | Examples |
|---|---|---|---|---|
| Thread per connection | stack (~64 KB–1 MB) | blocks only that thread | yes | classic Apache prefork/worker, Tomcat |
| Event loop | a few KB | blocks everyone | one loop per core | nginx, Node.js, Redis, asyncio |
| Virtual threads / goroutines | a few KB | parks the goroutine | yes | Go, Java 21 |
See I/O models for select, poll, epoll and io_uring in detail.
Concurrency vs parallelism
- Concurrency: tasks overlap in time (may interleave on one core).
- Parallelism: tasks execute simultaneously on multiple cores.
Amdahl's law limits parallel speedup: if a fraction p of the work can be parallelised across n cores, speedup = 1 / ((1 − p) + p/n). With p = 0.9, even infinite cores give at most 10×. Serial sections (locks, coordination) dominate at scale.
Language-specific notes
| Runtime | Threads | Notes |
|---|---|---|
| CPython | 1:1 OS threads + GIL | threads help I/O, not CPU-bound Python; use processes or free-threaded 3.13+ build |
| Java | platform threads (1:1) + virtual threads (M:N, Java 21) | java.util.concurrent is the gold-standard toolkit |
| Go | goroutines (M:N, ~2 KB starting stacks) | channels + sync; GOMAXPROCS = cores |
| Node.js | single event loop + libuv thread pool (4 by default) for fs/DNS/crypto | worker_threads for CPU work |
| Rust | 1:1 threads; async via Tokio (M:N tasks) | ownership rules prevent data races at compile time |
Common threading bugs (preview)
- Race conditions on shared variables → Synchronization.
- Deadlocks from inconsistent lock order → Deadlocks.
- False sharing: two threads write different variables on the same 64-byte cache line, causing the line to ping-pong between cores. Fix with padding/alignment.
- Thread leaks: threads that never exit (missing
join, blocked forever). - Blocking the event loop with CPU work or synchronous I/O.
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.