为什么malloc从某个阈值开始依赖mmap? [英] Why does malloc rely on mmap starting from a certain threshold?

查看:277
本文介绍了为什么malloc从某个阈值开始依赖mmap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一些有关malloc的内容,并在malloc的手册页中找到了以下内容:

I was reading a little bit about malloc and found the following in the malloc's man page:

通常,malloc()从堆中分配内存,并调整 使用sbrk(2)根据需要调整堆的大小.分配块时 大于MMAP_THRESHOLD字节的内存,glibc malloc() 实现将内存分配为私有匿名映射 使用mmap(2).默认情况下,MMAP_THRESHOLD为128 kB,但 可使用mallopt(3)进行调整.使用mmap(2)执行的分配是 不受RLIMIT_DATA资源限制的影响(请参阅getrlimit(2)).

Normally, malloc() allocates memory from the heap, and adjusts the size of the heap as required, using sbrk(2). When allocating blocks of memory larger than MMAP_THRESHOLD bytes, the glibc malloc() implementation allocates the memory as a private anonymous mapping using mmap(2). MMAP_THRESHOLD is 128 kB by default, but is adjustable using mallopt(3). Allocations performed using mmap(2) are unaffected by the RLIMIT_DATA resource limit (see getrlimit(2)).

所以基本上从阈值MMAP_THRESHOLD开始,malloc开始使用mmap.

So basically starting from the threshold MMAP_THRESHOLD malloc start using mmap.

  1. 是否有任何理由要大块切换到mmap?
  2. 这会影响流程执行性能吗?
  3. mmap系统调用是否会强制进行上下文切换?

推荐答案

(1)可以通过munmap释放通过匿名mmap获取的页面,这正是glibc所做的.因此,对于较小的分配,free将内存返回到进程的堆中(但将它们保留在进程的内存中).对于较大的分配,free将内存整体返回给系统.

(1) Pages acquired via anonymous mmap can be released via munmap, which is what glibc is doing. So for small allocations, free returns memory to your process's heap (but retains them in the process's memory); for large allocations, free returns memory to the system as a whole.

(2)通过匿名mmap获取的页面只有在您首次访问它们时才被实际分配.在这一点上,内核必须将它们清零以避免在进程之间泄漏信息.因此,是的,与通过进程堆回收的页面相比,mmap所获取的页面第一次访问的速度较慢.是否会注意到差异取决于您的应用程序.

(2) Pages acquired via anonymous mmap are not actually allocated until you access them the first time. At that point, the kernel has to zero them to avoid leaking information between processes. So, yes, the pages acquired by mmap are slower to access the first time than those recycled through your process's heap. Whether you will notice the difference depends on your application.

不使用mmap的代价是释放的内存仍然被您的进程占用,并且系统上其他进程不可用.因此,这最终是一个权衡.

The cost of not using mmap is that freed memory is still tied up by your process and unavailable to other processes on the system. So this is ultimately a trade-off.

(3)它不会强制"上下文切换,而且我相信不太可能引起上下文切换. mmap实际上并不分配页面;它只是为您的过程操纵页面映射.那通常应该是非阻塞操作. (尽管我承认我对此不是100%肯定.)

(3) It does not "force" a context switch and is, I believe, unlikely to cause one. mmap does not actually allocate the pages; it just manipulates the page map for your process. That should typically be a non-blocking operation. (Although I admit I am not 100% sure about this.)

这篇关于为什么malloc从某个阈值开始依赖mmap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆