Cache 的 write back 和 write through

Loading

同事突然跟我說 write back 和 write through 這兩個詞出來,我知道他是跟 cache 相關但我有點忘記這兩者的不同.上 wiki 查了一下 write back 和 write through http://en.wikipedia.org/wiki/Cache

  • write-through cache
    write-through cache, every write to the cache causes a synchronous write to the backing store.
    使用 write-through 的 cache,,資料寫入cache時也會同步寫入儲存裝置
  • write-back
    Alternatively, in a write-back (or write-behind) cache, writes are not immediately mirrored to the store. Instead, the cache tracks which of its locations have been written over and marks these locations as dirty. The data in these locations are written back to the backing store when those data are evicted from the cache, an effect referred to as a lazy write.
    而 write-back 是將資料量儲存到一定的量之後,會依據同區塊的資料一次整批寫回去.裡面有提到 dirty ,他是在記憶體裡面 cache 的一個 bit 用來指示這筆資料已經被 CPU 修改過但是尚未回寫到儲存裝置中.

通常使用 write-back 會比 write-through 來得有效率,但write-back需要承擔斷電時cache裡的資料遺失的風險.

不過這 cache 有可能指的是 CPU 的 cache 也有可能是 Disk 的 cache.

  • CPU cache
    首先要提到的是 cache hit 與 cache miss,當 CPU 要從記憶體中讀取某一筆資料時,此時 cache 正好有這一筆資料,稱為 cache hit ,但反之 cache 無此筆資料時則稱為 cache miss,當 cache miss 時

    • 讀取資料
      讀取資料的方式有兩種,一種是將資料直接從記憶體讀進 CPU 此種稱為 read through .另外一種則是將資料寫入到 cache 從,CPU 再從 cache 讀取資料,此種方式稱為 no read through
    • cache hit 的資料寫入
      剛剛是讀取那寫入時的情況又是如何呢!! 當 CPU 要寫入資料到記憶體時,如果資料是 cache hit 的情況,第一種是 write through 資料將會一比一比立即寫入到 cache 和記憶體中,另外一種則是 write back ,資料會暫存在 cache 中,然後同一區塊的資料整批一次寫回記憶體中.
    • cache miss 的資料寫入
      不過當 cache miss 時,第一種是 no write allocate,資料會直接寫到主記憶體中,不會保留資料在 cache中,另一種方式是 write allocate ,資料會從主記憶體中載入到 cache,然後再依據 cache hit 的規則,將資料寫出.
  • Disk cache
    IDE 和 SATA 的硬碟也有所謂的 write back 和 write through 不過在 Linux 我們只能將 disk cache 的功能開啟或是關閉 無法更改他的模式,必須在 BIOS 下做修改.
    在 #dmesg 可以看到目前的 cache 模式為何.

    [root@benjr ~]# dmesg |grep -i write
    sda: Write Protect is off
    SCSI device sda: drive cache: write through
    sda: Write Protect is off
    SCSI device sda: drive cache: write through
    

    透過 #hdparm -W0/1 可以將 cache 功能關閉

    [root@benjr ~]# hdparm -W0 /dev/sda
    /dev/sda:
    setting drive write-caching to 0 (off)
    [root@benjr ~]# hdparm -W1 /dev/sda
    /dev/sda:
    setting drive write-caching to 1 (on)
    
沒有解決問題,試試搜尋本站其他內容

2 thoughts on “Cache 的 write back 和 write through

  1. write-through cache, every write to the cache causes a synchronous write to the backing store.
    個人對這句話的解釋是….
    使用 write-through 的 cache,資料寫入cache時也會同步寫入儲存裝置。

    通常使用write-back會比write-through來得有效率,但write-back需要承擔斷電時cache裡的資料遺失的風險。

    給版大參考囉~~~

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料