Threads and the Scheduler

Topics Covered

What a Thread Is

The parts of a thread

Kernel threads and user threads

What a thread costs

Thread states

Joining, detaching and thread lifetime

Threads are the basic unit of execution that an operating system schedules onto processor cores. Every other concurrency model in this course, from thread pools to goroutines to async tasks, eventually runs on top of a handful of operating system threads. Understanding what a thread consists of, what it costs and how the kernel decides which thread runs where explains a surprising amount of real world performance behavior, from why a server with ten thousand threads falls over to why a latency sensitive service pins its threads to specific cores.

The parts of a thread

A thread is an independent sequence of instructions with its own execution state. That state consists of a program counter that says which instruction runs next, a set of processor registers, a stack that holds local variables and return addresses for the chain of function calls in progress, and a small amount of kernel bookkeeping: a thread identifier, a scheduling priority, a signal mask and a pointer to thread local storage. Everything else belongs to the process and is shared by all of its threads: the heap, global variables, open files and sockets, memory mappings, the current directory and the user identity.

That split is the essence of threads. Because they share the heap and globals, threads in the same process can communicate by reading and writing ordinary memory, with no copying and no system calls. Because each has its own stack and registers, each can be in the middle of a different function call, waiting for a different event. A process with one thread behaves like a classic sequential program; adding threads adds more independent points of execution over the same memory.

Each thread has its own stack, registers and program counter. The heap, globals and file descriptors belong to the whole process.

Kernel threads and user threads

On Linux, a thread is a kernel task created with the clone system call and flags that tell the kernel to share the address space, file table and signal handlers with the parent. The kernel does not really distinguish threads from processes: both are tasks, and threads are simply tasks that share most of their resources. The pthreads library in glibc wraps clone, allocates the stack and sets up thread local storage. Windows and macOS have their own thread APIs with similar semantics.

Language runtimes build on these kernel threads in different ways. In Java before virtual threads, C++ std::thread, Rust std::thread and Python threading, each language thread is one kernel thread, a one to one mapping. Go, Erlang, Java virtual threads and many async runtimes multiplex many lightweight user level tasks onto a small pool of kernel threads, an M to N mapping, with a scheduler inside the runtime deciding which task runs on which kernel thread. The one to one model is simple and lets the kernel make every scheduling decision; the M to N model makes tasks far cheaper at the cost of a second scheduler that must cooperate with the kernel.

What a thread costs

Threads are not free. Each kernel thread needs a stack, and by default glibc reserves 8 MB of virtual address space for it, of which only the pages actually touched become resident memory, typically tens of kilobytes for a shallow call chain. Java reserves 1 MB per thread by default on most platforms. Creating a thread takes on the order of ten to fifty microseconds, because the kernel must allocate structures, map the stack and register the task with the scheduler. Each runnable thread also adds work for the scheduler and increases the chance of context switches.

These costs set practical limits. A server that creates one thread per connection works well for hundreds or a few thousand connections. At tens of thousands, memory for stacks, kernel task structures and scheduler overhead add up, and creating and destroying threads for short requests wastes a large fraction of time. Linux has a system wide limit on tasks, governed by kernel.threads-max and pid_max, and per user limits from ulimit, so a runaway program can fail with errors such as cannot create native thread long before it runs out of memory. Thread pools, discussed in a later lesson, exist largely to amortize these costs.

Each thread costs stack memory, kernel structures and scheduler work. At tens of thousands, the overhead dominates.

Thread states

At any moment a thread is in one of a few states. A running thread is executing on a core right now. A runnable, or ready, thread could run but is waiting for a core. A blocked thread is waiting for something other than a core: a lock, a disk read, a network packet, a timer, or a child process. A terminated thread has finished but may not yet have been joined and cleaned up. The scheduler moves threads between running and runnable; events such as a lock release or an arriving packet move them from blocked to runnable.

This model explains many observations. Load average on Linux counts runnable threads plus threads in uninterruptible disk sleep, so a load of 32 on a 16 core machine means roughly twice as much runnable work as there are cores. A thread blocked on a socket consumes no CPU at all, which is why I/O bound servers can have many more threads than cores without being slow. A thread that spins in a loop checking a flag stays runnable or running the whole time and burns a core, which is why waiting should almost always block rather than spin.

The scheduler moves threads between running and runnable. Waiting for I/O or a lock moves a thread to blocked until the event arrives.

Joining, detaching and thread lifetime

A thread that starts other threads usually needs to know when they finish and what they produced. Joining a thread waits for it to terminate and collects its result or exit status. A detached thread runs independently and cleans up after itself, but nothing can wait for it or observe its failure. Detached threads are a common source of trouble: a process may exit while a detached thread is halfway through writing a file, and an exception in a detached thread may be printed to a log nobody reads while the work silently never happens. Later lessons argue for structured concurrency, where every thread or task has a clear owner that waits for it, precisely to avoid orphaned work.

Thread exceptions deserve special attention. In Java, an uncaught exception in a thread terminates that thread only, and the rest of the program keeps running, possibly with a broken invariant. In C++, an exception that escapes a std::thread function calls std::terminate and kills the whole process. In Python, an exception in a threading.Thread prints a traceback and the thread ends, while the main thread carries on unaware. Every threaded program needs a deliberate policy for failures in background threads, usually by catching exceptions at the top of the thread function and reporting them to an owner that can decide what to do.

Thread identifiers and names are worth setting deliberately. Most runtimes let a program name its threads, and those names appear in debuggers, profilers, thread dumps and the output of top with the H flag. A thread dump of a production service with two hundred threads named Thread 17 through Thread 216 is nearly useless; one with names such as http worker 3, db pool 7 and metrics flusher makes problems obvious at a glance.

Know the cost and state of every thread you create

A thread is a program counter, registers and a stack over the shared memory of its process. Kernel threads cost tens of kilobytes of resident stack, tens of microseconds to create and scheduler work while runnable. Threads move between running, runnable and blocked, and blocked threads cost no CPU. Give every thread an owner that joins it and handles its failures.