programmingconcepts

§ 6.1 · Concurrency

Threads

Separate paths of execution inside one program, each with its own stack, all sharing the same memory.

A thread is a sequence of instructions that runs independently inside a program. One process can run many threads; each has its own call stack, but all share the same heap memory. The operating system schedules them, running them in parallel on several CPU cores or switching between them on one. Shared memory makes threads fast but risks race conditions.

Owns
A stack, registers, a program counter
Shares
Heap memory, open files, the process
Scheduled by
The operating system
Start and wait
start, then join
Requires
FunctionsStack vs heap

Both threads add 1 to counter, which starts at 0. Pick which thread runs its next line.

step 0 / 0ran lastreadwritten

Fig. 6.1. You are the scheduler. Two threads run the same three lines, and Run A or Run B picks which one runs its next line. Each thread keeps its own tmp; counter is shared memory.

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:

  1. Start a thread with a function to run. The call returns immediately, and the function runs alongside the code that started it.
  2. 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)

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

  1. Forgetting to join. The main program can finish, or read the results, before the threads are done.
  2. 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.
  3. Assuming an order. Two threads started in order A, B can run in any order. Never rely on it.
  4. 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?

Check yourself

Thread B is started after thread A. Which one finishes 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).

Newsletter

One new concept each week, by email.

Signup opens soon.