C++如何从RAM中解开未使用的全球阵列?
在C ++中,当您声明一个大数组时,例如500MB,它不会立即映射到RAM,因为它尚未使用。一旦我第一次访问阵列的页面,它就会映射到物理内存。现在,系统知道我正在使用该页面,但是我如何告诉系统我不再使用某个页面,并且可以按照其意愿将其拆除?
就我而言,我只需要偶尔,所以并非所有时间都需要填充一个大数组,然后在快速随机访问中进行操作。现在我可以每次都使用Malloc,但是为什么要这样做呢?有多种方法可以告诉系统您不需要某个页面,但是它们既可以将其从物理空间和虚拟空间删除。我只想将其从物理空间中解开。不可能吗?
In C++ when you declare a big array, say 500MB, it doesn't get mapped to RAM immediately because it is not used yet. As soon as I access a page from the array for the first time, it gets mapped to physical memory. Now the system knows that I am using that page, but how do I tell the system that I am not using some page anymore and that it can unmap it at its will?
In my case I just need to occasionally, so not all the time, fill a big array and operate on it with fast random access. Now I could use malloc every time, but why would I do that? There are ways to tell the system that you don't need some page, but they all both unmap it from physical space and virtual space. I just want to unmap it from physical space. Is it not possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无需做任何特别的事情。
内存管理单位会根据需要自动将虚拟内存页面移入物理RAM。如果一段时间没有使用页面,并且需要其他内容的内存,则将其分类。物理RAM包含最近使用的页面,如果由文件支持(例如程序的文本段),或者将其写入磁盘的交换区域然后被驱逐出境,则较旧的页面被驱逐出境。
完成整个数组后,应使用
delete []
对其进行处理。根据内存分配器的设计,可能也可能不会从虚拟内存中删除内存页面,但是您对此没有任何直接控制。如果您谈论的是静态阵列,则无法表明您已经完成了它。如果需要执行此操作,则必须使用
new
动态分配数组,以便delete
it。You don't need to do anything special.
Memory management units automatically move virtual memory pages in and out of physical RAM as needed. If a page hasn't been used in a while, and its memory is needed for something else, it will be paged out. Physical RAM holds the pages that have been used most recently, older pages are just evicted if they're backed by a file (e.g. the text segment of programs), or they're written to the swap area of disk and then evicted.
When you're done with the entire array you should deallocate it with
delete[]
. Depending on the design of the memory allocator this may or may not remove the memory pages from your virtual memory, but you don't have any direct control over that.If you're talking about a static array, there's no way to indicate that you're done with it. If you need to do that, the array must be allocated dynamically with
new
so you candelete
it.经过大量研究,幸运的是,我发现了另一个,在暴露于
mmap()
的情况下,用map_anon | map_shared
选项将数组分配和madvise()
用MADV_REMOVE
选项可以做到这一点。您可以查看男子页面以获取详细信息。After a lot of research, luckily, I found another post, where it is exposed that using
mmap()
withMAP_ANON|MAP_SHARED
option to allocate the array andmadvise()
withMADV_REMOVE
option does the trick. You can check the man-pages for details.