{}DSA Atlas

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.

Intermediate8 interview questions

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:

  1. Responsiveness — keep a UI or server responsive while work happens in the background.
  2. Parallelism — use multiple CPU cores for one task.
  3. Overlapping I/O with computation — one thread waits for disk/network while another computes.
  4. Cheaper than processes — creation and switching avoid copying address spaces.
Single-threaded process code data files registers stack Multi-threaded process code data / heap files registers stack registers stack registers stack
Threads share code, heap and files (orange); each has its own registers and stack (blue).

Process vs thread

ProcessThread
Address spaceownshared with siblings
Creation costhigh (fork, page tables)lower (clone with shared VM)
Context switchhigher (address space + TLB)lower
CommunicationIPC (pipes, sockets, shm)shared memory directly
Fault isolationcrash affects only itselfcrash kills all threads
Synchronization neededrarelyalways 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

ModelMappingExamplesProsCons
N:1many user threads → 1 kernel threadearly Java green threads, GNU Pthvery cheap switchesno parallelism; one blocking call blocks all
1:1each user thread = kernel threadLinux pthreads (NPTL), Windows, Java platform threadsreal parallelism; simpleheavier (syscalls to create, ~8 MB stack reservation)
M:NM user threads on N kernel threadsGo, Java virtual threads, Erlang, Tokio taskscheap + parallelcomplex 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:

Python
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())
ModelMemory per connectionBlocking a handlerMulti-coreExamples
Thread per connectionstack (~64 KB–1 MB)blocks only that threadyesclassic Apache prefork/worker, Tomcat
Event loopa few KBblocks everyoneone loop per corenginx, Node.js, Redis, asyncio
Virtual threads / goroutinesa few KBparks the goroutineyesGo, 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

RuntimeThreadsNotes
CPython1:1 OS threads + GILthreads help I/O, not CPU-bound Python; use processes or free-threaded 3.13+ build
Javaplatform threads (1:1) + virtual threads (M:N, Java 21)java.util.concurrent is the gold-standard toolkit
Gogoroutines (M:N, ~2 KB starting stacks)channels + sync; GOMAXPROCS = cores
Node.jssingle event loop + libuv thread pool (4 by default) for fs/DNS/cryptoworker_threads for CPU work
Rust1: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

0 / 8 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.