In this article, you will discover what virtual memory is and how processes and threads access your computer’s RAM.
Virtual memory is a virtual layer between threads and RAM, providing controlled interaction between threads and RAM.
Threads and virtual memory
In this article I said about threads that every thread has pointers to memory.
Since often a lot of memory is required, the OS developers decided to divide the memory for each thread into pages. Each page of memory has its own page number.
But pages can be large, so they introduced another concept: offset, which indicates the position of the desired memory area in the memory page.
It can be show in this diagram:
RAM itself has frames instead of pages. This is a direct memory area. And pointers to frames are called addresses.
Now let’s consider the diagram of interaction threads with virtual memory and physical memory (RAM and SWAP):
Threads with their memory (page number and offset) are shown in green shapes. All threads requests go through the MMU.
MMU (Memory Management Unit) is a memory management unit that has a table of all virtual memory pages and methods for calling swapping (unloading data from RAM to swap on HDD / SSD).
The MMU receives the page number and offset of the thread and matches the page number and offset to virtual memory. And virtual memory already transfers the address space and offset of physical memory or paging.
In the process of granting access to RAM, an error may occur — Page fault. It occurs in situations where a process is accessing a frame that is not in RAM. In this case, the MMU calls an interrupt and load the pages from SWAP.
Advantages of virtual memory:
- Issuing dynamic address spaces, since threads most often do not use the memory available to them, but in rare cases they may require excess memory. If there was no virtual memory, memory in RAM would be divided statically between threads, which again leads to memory consumption by threads
- Security following from the first point
- Parts of the used memory can be used at different times, that is, there is no static memory sharing by threads Virtual memory can refer to paging, thereby increasing the amount of memory available to threads
- Performance. A new level of abstraction — virtual memory — always means an increased call stack.