HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

How is data written to RAM

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
ramdatawrittenhow

Problem

From my understanding(correct me if I am wrong) when I read data from RAM memory it is copied into processor cache and than it is copied into register to be used by the processor. When I create data (like variable) is it first created in register and than copied to cache and from cache to RAM or is it directly created in RAM?

Additional question:Does stack and heap exist only in RAM or do they exist in processor cache as well?

Solution

When you read data from a given memory address, the memory manager checks if there is a copy in the cache. If yes (cache hit), the copy is read into the register. If no (cache miss), the cache is first updated with a row of memory from RAM; then the data can be read into the register.

Conversely, when you write to a memory address, the data is just written to the cache, making room if required. Later, when the cache line must be freed or is explicitly flushed, the row of memory is copied to RAM.

If you perform successive reads and writes to the same address, it can very well arise that all changes are made in the cache and the RAM left untouched. From the processor's point of view, the presence of the cache is transparent. It just reads from and writes to memory addresses, and the memory manager optimizes the transfers.

Note that you don't "create" data in memory. When a program is loaded, some RAM space is assigned to it and reserved (possibly also initialized), and the addresses of the variables are "mapped" onto that space. Then the program is allowed to write to or read from these addresses.

In modern, multicore CPUs, cache management is much more complicated because several concurrent reads/writes to the same memory addresses can occur. The MMU must ensure that all caches and RAM remain coherent and "synchronize" their content.

The stack and the heap have a range of memory addresses allocated, and they are handled through the cache like ordinary program space. The stack is an essential resource during program execution and it is extremely frequently accessed. It is important that it be cached as well.

Context

StackExchange Computer Science Q#28987, answer score: 8

Revisions (0)

No revisions yet.