THINK FIRST·CODE LATER

← All labs

Write-back vs. write-through cache

Problem

Simulate a block cache with LRU replacement.

Input: policy (through or back), capacity (blocks), then operations: read b, write b, sync, crash.

  • read b: hit if cached; on a miss, read the block from disk (disk read) and insert it.
  • write b: a miss inserts the block without reading it (full-block write). With through, the block is written to disk immediately (disk write) and stays clean; with back, it becomes dirty.
  • Eviction (when inserting into a full cache): remove the least recently used block; if it is dirty, write it to disk (disk write).
  • Print read 3: miss / write 1: hit for each read/write.
  • sync: write all dirty blocks, mark them clean: sync: 2 dirty blocks written (singular block for 1).
  • crash: print CRASH: lost updates to blocks [4, 5] (sorted dirty blocks, or none) and empty the cache.

At the end: Operations: n, hits: h, disk reads: r, disk writes: w (reads and writes only count as operations).

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.