Skip to content

Processes, threads and what the OS schedules

BasicsUnder the hood

Your machine runs hundreds of programs on a few cores. Here is what a process and a thread really are, and what the kernel does each time it swaps one for another.

01 Hundreds of programs, a handful of cores

Count what is running on a Linux machine and compare it with the number of CPU cores. There are far more programs than cores, yet they all seem to make progress at once.

Shell
$ nproc
8
$ ps -e --no-headers | wc -l
312

A core runs one stream of instructions at a time. The trick is that the kernel keeps swapping which stream that is, many times a second. To see how, you need two words that people often mix up: process and thread.

02 A process is a private memory space

When you start a program, the kernel makes a process: a private address space (the program’s code, its heap and its stacks), a table of open files, a process ID and a few limits. Address 0x4a10 in one process and 0x4a10 in another are different bytes of RAM. The CPU’s page tables do that translation, and each process has its own.

A thread is one stream of instructions running inside a process. It has only what it needs to execute: its own registers (including the program counter, which says where it is in the code) and its own stack. Everything else it shares with the other threads in the same process.

Who owns what
ThingPer processPer thread
Code, heap, global variablesyes, shared by its threadsno
Open files and socketsyesno
Process ID (PID)yeseach has a thread ID too
Registers and program counternoyes
Stack (local variables)noyes

On Linux the scheduler does not really tell the two apart. Every thread is a task with its own task_struct. A process is simply a group of tasks that point at the same memory. A single-threaded program is a process with one task.

03 What a context switch does

The kernel lets a task run for a short slice of time, then stops it and runs another. Swapping one task out for another is a context switch. Watch one core run three tasks: two threads of process P1 and the only thread of process P2.

Context switches on one core
Step 1 of 9
Switches 0
CPU core 0 · registers
runs A
PC 0x4a10
SP 0x7f10
pages: P1
Kernel task list (task_struct)
statesaved PCmemory
A · thread of P1running—P1
B · thread of P1ready0x4b20P1
C · process P2ready0x1c00P2
  • on the CPU now
  • looked at
  • just saved or loaded
  • running at the end

Thread A of process P1 is running on core 0. Its registers live in the CPU itself; B and C wait in the kernel with their registers saved from the last time they ran.

A running
Thread → thread, same processRegisters onlyThe memory stays the same, so the CPU caches and address translations are still useful.
Process → processRegisters + memory mapThe page tables change, so translations cached for the old process stop helping and the new one starts colder.

Either kind typically costs a few microseconds once you count the cache misses afterwards. That is nothing once, but a server that switches hundreds of thousands of times a second spends real CPU on it.

04 Threads share memory, for better and worse

Because threads share one address space, one thread can hand data to another just by writing it to a variable. No copying, no messages. The same fact causes the classic bug: the kernel can switch threads between any two instructions, including in the middle of what looks like one line of code.

Two threads, one counter
Step 1 of 7
Shared memory · counter
0
Each thread’s own registers
registernext
thread T1—load
thread T2—load
  • about to run
  • read from memory
  • just written
  • final value

Two threads of one process both run counter += 1. That one line is really three CPU steps: load the value, add one, store it back.

T1 on the CPU

The fix is to make the three steps one: a lock around the update, or an atomic increment instruction. Separate processes do not have this problem with ordinary variables, because they do not share them at all.

05 See it yourself

This Python script bumps a global once in a thread and once in a child process. The thread changes the parent’s variable. The child process changes its own copy, which vanishes when it exits.

share.py
import threading
import multiprocessing
counter = 0
def bump():
global counter
counter += 1
if __name__ == "__main__":
t = threading.Thread(target=bump)
t.start(); t.join()
print("after thread: ", counter)
p = multiprocessing.Process(target=bump)
p.start(); p.join()
Text
$ python3 share.py
after thread: 1
after process: 1

On Linux, /proc/<pid>/status shows how many threads a process has and how often it has been switched out. Voluntary switches happen when the task waits (for disk, a socket, a lock). Non-voluntary ones happen when the kernel takes the core away because its time slice ran out.

Shell
$ grep -E 'Threads|ctxt' /proc/1234/status
Threads: 4
voluntary_ctxt_switches: 5120
nonvoluntary_ctxt_switches: 37

06 When it bites

counter += 1Unprotected shared stateAny read-modify-write on shared memory can lose updates, as in the trace. Use a lock, an atomic, or give each thread its own data.
Segmentation faultOne thread crashes them allA bad memory access in any thread kills the whole process, because they share one address space. Separate processes fail alone.
10,000 threadsToo many threadsEach thread needs its own stack and a turn on a core. Past a point the machine spends more time switching than working. This is why servers use thread pools or an event loop.
threading.Thread(...)Python threads and the GILIn standard CPython, the global interpreter lock lets only one thread run Python code at a time. Threads still help while waiting on I/O, but CPU-heavy work needs processes (or a free-threaded build, 3.13 and later).

07 Check yourself

Question

Thread T1 sets a global variable ready = True. Can thread T2, in the same process, read the new value?

Question

Which context switch is usually cheaper?

Question

A program has 8 threads. One of them reads from an invalid pointer. What dies?

08 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?