c++ - 是否有任何操作系统允许将内存从一个地址移动到另一个地址而无需物理复制它?

标签 c++ c windows linux operating-system

memcpy/memmove duplicate(复制数据)从源到目标。是否存在将页面从一个虚拟地址移动到另一个虚拟地址而不对源数据进行实际逐字节复制的方法?这对我来说似乎是完全可能的,但是任何操作系统实际上都允许这样做吗?动态数组是一个如此广泛和流行的概念,但通过物理复制来增长它们却是一种浪费的操作,这对我来说似乎很奇怪。当您开始谈论以千兆字节为单位的阵列大小时,它只是无法扩展(例如,想象一下将一个 100GB 的阵列增长到一个 200GB 的阵列。现在这个问题在 < 10,000 美元范围内的服务器上完全可能发生。

void* very_large_buffer = VirtualAlloc(NULL, 2GB, MEM_COMMIT);
// Populate very_large_buffer, run out of space.
// Allocate buffer twice as large, but don't actually allocate 
// physical memory, just reserve the address space.
void* even_bigger_buffer = VirtualAlloc(NULL, 4GB, MEM_RESERVE);
// Remap the physical memory from very_large_buffer to even_bigger_buffer without copying
// (i.e. don't copy 2GB of data, just copy the mapping of virtual pages to physical pages)
// Does any OS provide support for an operation like this?    
MoveMemory(very_large_buffer, even_bigger_buffer, 2GB)
// Now very_large_buffer no longer has any physical memory pages associated with it
VirtualFree(very_large_buffer)

最佳答案

在某种程度上,您可以使用 mremap 来做到这一点在 Linux 上。

如果可以的话,该调用会使用进程的页表进行零拷贝重新分配。。并非在所有情况下都可行(地址空间碎片,以及其他现有映射的存在本身就是一个问题)。

手册页实际上是这样说的:

mremap() changes the mapping between virtual addresses and memory pages. This can be used to implement a very efficient realloc(3).

关于c++ - 是否有任何操作系统允许将内存从一个地址移动到另一个地址而无需物理复制它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8618833/

相关文章:

c++ - 将静态库和动态库链接到同一个可执行文件会导致什么问题?

c++ - Visual C++ 2017(版本 15.9.3)中出现错误

c++ - 多重定义,这里已经定义

c++ - 如何正确删除模板函数中的代码重复

c# - "add as link"选项发生了什么?

python - 可用内存和总内存始终相同

c - 哪些 int 值与 C 中的 exit() 相关?

c - 如果打开文件,fopen() 会返回什么文件指针?

用于信号处理和用户管理的 Python Unix/Windows 抽象层

c - 为什么 getopt 库中没有 <string.h>?