Why is exact LRU expensive, and how does the clock algorithm approximate it?
HardConceptPage Replacement & Thrashing
Answer
Exact LRU must record the order of every memory access, for example with a timestamp per page, and find the least recently used page on each fault. Doing that on every access, billions of times per second, is too slow in software, and few CPUs support it in hardware.
- Hardware instead offers a cheap hint: a reference (use) bit per page, set to 1 whenever the page is accessed.
- Clock (second chance): frames form a circle with a pointer, the "clock hand". On a fault, check the page under the hand: if its bit is 1, clear it to 0 and move on (a second chance); if it is 0, evict that page.
- Recently used pages survive at least one sweep, so the result is close to LRU at very low cost. An enhanced version also prefers clean (unmodified) pages, which need no write-back; Linux uses a similar idea with active and inactive page lists.
Example: frames hold A (bit 1), B (bit 0) and C (bit 1), with the hand at A. On a fault for page D, A's bit is cleared to 0 and the hand moves on; B's bit is 0, so B is evicted and D takes its place. The frames are now A (0), D (1) and C (1), with the hand at C.
More in Page Replacement & Thrashing
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | Compare FIFO, LRU and Optimal page replacement. | Concept | Medium | Read the answer to Compare FIFO, LRU and Optimal page replacement. | |||
| 2 | What is Belady's anomaly? | Concept | Medium | Read the answer to What is Belady's anomaly? | |||
| 3 | Why is exact LRU expensive, and how does the clock algorithm approximate it? | Concept | Hard | Read the answer to Why is exact LRU expensive, and how does the clock algorithm approximate it? | |||
| 4 | What is thrashing, why does it happen, and how can it be prevented? | Concept | Hard | Read the answer to What is thrashing, why does it happen, and how can it be prevented? |