Working sets
RAM is split into page frames, here just six, and every running program keeps its pages in them. A page that is not in RAM waits in swap on the disk. Touching it is a page fault: the kernel must fetch it first.
A program uses only a few pages at a time. Its working set is the pages it touched in its last few references, here the last 4. Program A loops over three pages, so its working set is a1, a2, a3: three frames.
When they fit
Programs A and B take turns, one reference each. Their working sets need 3 + 3 = 6 frames, and RAM has 6. The first touch of each page faults and loads it from swap: 6 faults, once.
Now every page A and B use is already in RAM. Each access takes about 100 nanoseconds and never waits for the disk. In the next 18 references not one faults, so the CPU spends its time on real work.
Thrashing
Program C starts and also needs three pages: 3 + 3 + 3 = 9 frames wanted, 6 available. C touches c1, which is not in RAM. To make room, LRU (least recently used) evicts the page used longest ago, a1.
A needs a1 next: fault, and LRU evicts b1. B needs b1: fault, evicting a2. C needs c2: fault, evicting b2. Every page thrown out is one a program will need a moment later.
Now every reference faults, and each fault waits about 10 milliseconds for the disk, 100,000 times longer than a RAM access. The programs only wait, and the CPU does useful work about 0.001% of the time. This is thrashing.
Getting out
The cure is admission control: run fewer programs. The kernel suspends C and swaps its pages out. A and B fit again: after 2 faults bring back their missing pages, every access hits and the CPU is busy again.
Linux measures the stalls: /proc/pressure/memory reports the share of time tasks wait for memory, and a long "full" stall, every task waiting at once, means thrashing. If memory runs out entirely, the out-of-memory killer ends a large process.
Add up the working sets of everything running and compare with RAM: 3 + 3 = 6 frames fits in 6, but 3 + 3 + 3 = 9 does not. When total demand exceeds RAM, the system thrashes; running fewer programs fixes it.
What happens
;; step 1/10 · shared
page frame one page-sized slot of RAM (4 KiB on most PCs)
swap disk space for pages that do not fit in RAM
page fault the page is not in RAM: the kernel reads it
from swap, maybe evicting another page first
this example: 6 frames, global LRU replacement
RAM access about 100 ns disk access about 10 ms (OSTEP)
The example is tiny on purpose: 6 frames, three programs of three pages, one reference per turn and exact LRU. Real machines have millions of frames and approximate LRU (for example with the clock algorithm), but the cliff is the same: once total demand passes RAM, faults take over. Useful work is worked out as 100 ns / (100 ns + fault rate x 10 ms): one disk serves the faults one at a time, and while every program waits for it the CPU has nothing to run. At a 100% fault rate that is about 0.001%.