Virtual memory lets a program use more memory than physically available by keeping only the needed pages in RAM (demand paging). Accessing a page that is not in RAM causes a page fault. Too many page faults = thrashing.
Example: reference string 7 0 1 2 0 3 0 4, 3 frames
| Algorithm | Idea | Page faults |
|---|---|---|
| FIFO | Replace the page that came in first | 7 |
| LRU | Replace the least recently used page | 6 |
| Optimal | Replace the page not needed for the longest time (theoretical best) | 6 |
Belady's anomaly: with FIFO, adding more frames can sometimes increase page faults.
int lruFaults(vector<int> refs, int frames) {
list<int> cache; // front = most recently used
int faults = 0;
for (int p : refs) {
auto it = find(cache.begin(), cache.end(), p);
if (it != cache.end()) cache.erase(it); // hit
else {
faults++;
if (cache.size() == frames) cache.pop_back(); // evict LRU
}
cache.push_front(p);
}
return faults;
}