So what about writing to memory?
When the processor writes data to memory it is always written to cache. Just like a cache read, the memory address is searched within the tags of the cache entries. During a write, if the address is found the data is overwritten in the cache. If it is not found the replacement policy is used to decide which entry will be replaced with the entry.
The decision of when to send data to the main memory is made by the cache write policy. Here are two common write policies:
Write-through
The write-through policy will write the data to the main memory at the same time it is written to cache. This policy is easy to implement since there are no decisions that need to be made after the data is written to cache. The downside is that every write will require a main memory access which is slower and sometimes unnecessary.
Write-back
The write-back policy will only write the data to the main memory when the memory address in the associated cache entry is overwritten. This policy is more complicated to implement because the data in cache now has to be monitored.
The benefit of the write-back policy is that every write does not access the main memory. It is possible for the processor to put data in the cache, access it multiple times, and not need it anymore without ever having to write it to the main memory. When using the write-back policy, this saves time over many write cycles.
Instructions
The Cache()
class has added the following:
- The
.write()
method with the parametersaddress
anddata
. - Inside
.write()
thesuper().write()
method is called to output the step taken and simulate the access time. - The
entry
variable is defined and assigned.get_entry(address)
.
Run the code. With an empty cache and no data actually being written to the cache or the main memory, all you will see is cache misses.
If the address exists in the cache, update the data in that entry.
Inside the write()
method:
- Replace
pass
withentry["data"]
and set it equal to the value indata
.
If the address does not exist in the cache, invoke the replacement policy.
Inside the write()
method:
- Add an
else
clause to theif
statement. - Inside the
else
clause, callself.replace_entry()
withaddress
anddata
as parameters.
The last step to implementing the write-through policy is to write the data to the main memory.
Inside the write()
method but outside the if
-else
clauses:
- Call
self.main_memory.write()
with the argumentsaddress
anddata
.
When you run the code you will see cache writes with misses and then memory writes. The data will then be read like the previous exercises.