Windows 虚拟内存技术常识

  虚拟内存技术,是现代计算机系统所不可缺少的技术,即使计算机拥有足够大的物理内存。“虚拟内存”在这里只是一个抽象的概念,并不是指某个硬件实物、软件实物,或硬件存储中被划分出的区域。虚拟内存的“内存”概念是针对应用程序的——应用程序在运行时会提出数据存储、提取请求,为了便于程序开发,一般都是假设有足够大的连续的存储空间,操作系统就为计算机提供了这样一个虚拟的空间,这种理想的存储空间称为虚拟内存。参照 Wikipedia 的原文解释:

Virtual memory is a computer system technique which gives an application program the impression that it has contiguous working memory, while in fact it may be physically fragmented and may even overflow on to disk storage. Systems that use this technique make programming of large applications easier and use real physical memory (e.g. RAM) more efficiently than those without virtual memory.

Note that "virtual memory" is not just "using disk space to extend physical memory size". Extending memory is a normal consequence of using virtual memory techniques, but can be done by other means such as overlays or swapping programs and their data completely out to disk while they are inactive. The definition of "virtual memory" is based on tricking programs into thinking they are using large blocks of contiguous addresses.

  虚拟内存最终还是依靠操作系统、物理内存、空余磁盘空间来实现。操作系统领导着整个“地址欺骗”过程,将应用程序的存储、读取请求分派给物理内存或特殊磁盘空间。由于操作系统的不同,虚拟内存的实现方式也有所差异。

  Linux 系统里,磁盘本身就有一个 Swap 分区,就是交换区。这是一个独立功能区,和文件系统完全分离。这个分区完全承担了虚拟内存在磁盘部分的所有角色。

  但是在 Windows 系统里,由于没有这种独立的分区,虚拟内存的实现就不那么显眼了。这时,虚拟内存在磁盘部分的所有角色都是被临时安插在文件系统里的。系统会在磁盘上开辟一个或多个交换空间(Swap Space),每个交换空间都会存放在文件系统里可见的所谓页面文件(Paging File)。用户可以设置页面文件的大小,但是却不能设置交换空间的大小,因为交换空间是根据页面文件大小和物理内存大小而定的,其大小要确保物理内存中可交换的所有数据可全部迁移到交换空间而交换空间中原本的页面文件没有被清理掉(即:比页面文件与物理内存大小之和略小)。而一般也就把物理内存和交换空间的大小之和称作虚拟内存大小(其实也不是一个很好的说法,但至少 Everest 是这么显示的)。由于交换空间的存在,以及 Windows 在紧急状况下可以扩大交换空间的能力(猜测),所以有的用户即使禁用页面文件,还是能看到“虚拟内存”的存在(真的物理内存写满又没别的存储,计算机就真永久死机直至重启了)。另外,将物理内存中的信息交换给页面文件,这种动作叫做分页(Paging),以下是 Wikipedia 的原文解释:

In computer operating systems that have their main memory divided into pages, paging (sometimes called swapping) is a transfer of pages between main memory and an auxiliary store, such as hard disk drive. Paging is an important part of virtual memory implementation in most contemporary general-purpose operating systems, allowing them to easily use disk storage for data that does not fit into physical RAM. Paging is usually implemented as a task built into the kernel of the operating system.