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:
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.
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.
Cache() class has added the following:
.write()method with the parameters
super().write()method is called to output the step taken and simulate the access time.
entryvariable is defined and assigned
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.
entry["data"]and set it equal to the value in
If the address does not exist in the cache, invoke the replacement policy.
- Add an
elseclause to the
- Inside the
The last step to implementing the write-through policy is to write the data to the main memory.
write() method but outside the
self.main_memory.write()with the arguments
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.