Intuition
A program normally runs one instruction after another, like a single cook following a recipe. Threads are extra cooks in the same kitchen. Each follows their own recipe at their own pace, but they share the fridge, the counter space and the oven.
That sharing is the point, and the danger. Cooks can hand each other ingredients instantly. They can also reach for the same pan at the same moment.
Threads vs processes
| Process | Thread | |
|---|---|---|
| What it is | A running program | A path of execution inside a process |
| Memory | Its own, isolated from other processes | Shared with the other threads in its process |
| Talks to others by | Pipes, sockets, files | Reading and writing the same variables |
| Cost to start | Higher | Lower |
| If it crashes | Other processes keep running | The whole process usually goes down |
Each thread gets its own call stack, so local variables are private. Everything on the heap, and every global, is visible to every thread.
The scheduler decides
You don’t control when a thread runs. The operating system’s scheduler does. On a machine with 8 cores, up to 8 threads run truly in parallel. When there are more threads than cores, the scheduler gives each a short time slice, then pauses it and switches to another, which is called a context switch.
A switch can happen between any two instructions. That’s what the figure lets you play with. Run thread A to the end, then B, and the counter is 2. Interleave them, and both read 0 before either writes, so it ends at 1. That lost update is a race condition, and it’s the main reason threaded code is hard.
Start, then join
Almost every language uses the same two steps:
- Start a thread with a function to run. The call returns immediately, and the function runs alongside the code that started it.
- Join the thread to wait until its function has finished.
The example splits a list into chunks, sums each chunk on its own thread, joins them all, and adds up the results. Each thread writes only to its own slot, so no two threads touch the same data and no lock is needed.
import threading
def parallel_sum(numbers, threads):
size = -(-len(numbers) // threads) # ceiling division
results = [0] * threads # one slot per thread, so no two threads write the same place
def work(index):
chunk = numbers[index * size:(index + 1) * size]
results[index] = sum(chunk)
workers = [threading.Thread(target=work, args=(i,)) for i in range(threads)]
for w in workers:
w.start() # work(i) now runs on its own thread
for w in workers:
w.join() # wait for that thread to finish
return sum(results)const { Worker } = require('node:worker_threads');
// Each Worker is a real OS thread running its own copy of the JavaScript engine.
// Workers don't share variables; they send messages instead.
function sumOnThread(chunk) {
const source = `
const { parentPort, workerData } = require('node:worker_threads');
parentPort.postMessage(workerData.reduce((a, b) => a + b, 0));
`;
return new Promise((resolve, reject) => {
const worker = new Worker(source, { eval: true, workerData: chunk }); // start the thread
worker.once('message', resolve);
worker.once('error', reject);
});
}
async function parallelSum(numbers, threads) {
const size = Math.ceil(numbers.length / threads);
const chunks = Array.from({ length: threads }, (_, i) => numbers.slice(i * size, (i + 1) * size));
const sums = await Promise.all(chunks.map(sumOnThread)); // wait for every thread
return sums.reduce((a, b) => a + b, 0);
}import "sync"
func parallelSum(numbers []int, threads int) int {
size := (len(numbers) + threads - 1) / threads
results := make([]int, threads) // one slot per goroutine, so no two write the same place
var wg sync.WaitGroup
for i := 0; i < threads; i++ {
wg.Add(1)
go func(i int) { // start a goroutine; Go spreads them over OS threads
defer wg.Done()
lo, hi := min(i*size, len(numbers)), min((i+1)*size, len(numbers))
for _, n := range numbers[lo:hi] {
results[i] += n
}
}(i)
}
wg.Wait() // wait for every goroutine to finish
total := 0
for _, r := range results {
total += r
}
return total
}use std::thread;
fn parallel_sum(numbers: &[i64], threads: usize) -> i64 {
let size = ((numbers.len() + threads - 1) / threads).max(1);
// A scope guarantees every thread finishes before the function returns,
// so the threads can safely borrow `numbers`.
thread::scope(|s| {
let handles: Vec<_> = numbers
.chunks(size)
.map(|chunk| s.spawn(move || chunk.iter().sum::<i64>())) // start a thread
.collect();
handles.into_iter().map(|h| h.join().unwrap()).sum() // wait for each one
})
}In each language
| Language | Threads | Notes |
|---|---|---|
| Python | threading.Thread |
The GIL lets only one thread run Python code at a time, so threads speed up waiting (network, files) but not computing. Use multiprocessing, or free-threaded Python 3.13+, for CPU work. |
| JavaScript | Worker (worker_threads in Node.js, Web Workers in browsers) |
Your code runs on one thread. Workers are separate threads that share nothing by default and talk by messages. For waiting on I/O, use async and await instead. |
| Go | go f() starts a goroutine |
Goroutines are lightweight, a few KB each, and Go spreads them over a few OS threads. Running 100,000 is normal. |
| Rust | std::thread::spawn, thread::scope |
The compiler checks that shared data is safe to share, so data races don’t compile. |
The cost of a thread
An OS thread isn’t free. Each one reserves memory for its stack, often 1 to 8 MB of address space, and every context switch costs time. A server that starts one thread per request falls over long before 100,000 requests. That’s why real programs use a thread pool: a fixed set of threads that take jobs from a queue. It’s also why Go’s goroutines and async/await exist: they handle huge numbers of waiting tasks on a few threads.
Common mistakes
- Forgetting to join. The main program can finish, or read the results, before the threads are done.
- Sharing data without a lock. Any data that more than one thread writes needs a lock, an atomic, or a redesign, like the separate slots in the example.
- Assuming an order. Two threads started in order A, B can run in any order. Never rely on it.
- Using threads to speed up Python number crunching. The GIL makes it no faster. Use processes or a library that runs outside the GIL, like NumPy.
Check yourself
Check yourself
Two threads in the same process each have a local variable count. Do they see each other's count?
Local variables live on the thread’s own stack. Threads share the heap and globals, not each other’s locals.
Check yourself
Thread B is started after thread A. Which one finishes first?
Starting order doesn’t fix running order. The scheduler can run, pause and resume threads in any order, so either can finish first.
Sources
- Andrew Tanenbaum and Herbert Bos, Modern Operating Systems, 4th edition, section 2.2, “Threads.”
- Remzi and Andrea Arpaci-Dusseau, Operating Systems: Three Easy Pieces, chapter 26, “Concurrency: An Introduction,” ostep.org.
- Rob Pike, “Concurrency is not Parallelism,” talk at Heroku Waza (2012).
Finished this page?
Your list