Linux内存管理

首先提供Gustavo Duarte写的三篇非常精彩的文章:

1. Anatomy of a Program in Memory

2. How The Kernel Manages Your

3. Page Cache, the Affair Between Memory and Files

然后看看Linux下malloc的实现原理:

1. Doug Lea. A Memory Allocator

2. ptmalloc原理分析

看完上面的文章,我们对Linux的内存管理就有了大概的印象,也知道了malloc和mmap对于OS而言意味着什么。剩下的有几个问题:

1. 在申请大于一定阈值(128K)时,malloc为什么要使用mmap

Efficiency Considerations for malloc 写道
As opposed to other versions, the malloc in the GNU C Library does not round up block sizes to powers of two, neither for large nor for small sizes. Neighboring chunks can be coalesced on a free no matter what their size is. This makes the implementation suitable for all kinds of allocation patterns without generally incurring high memory waste through fragmentation.

Verylargeblocks(muchlargerthanapage)areallocatedwithmmap(anonymousorvia/dev/zero)bythisimplementation.Thishasthegreatadvantagethatthesechunksarereturnedtothesystemimmediatelywhentheyarefreed.Therefore,itcannothappenthatalargechunkbecomes"locked"inbetweensmalleronesandevenaftercallingfreewastesmemory.Thesizethresholdformmaptobeusedcanbeadjustedwithmallopt.Theuseofmmapcanalsobedisabledcompletely

2. 处理文件时,是不是使用memory-mapped-file都要优于标准IO

    关于这个问题,可以先了解一下memory mapped file 的优缺点。一个明显的问题是当文件大于虚拟地址空间时,将无法一次性将文件映射到虚拟地址空间里面。此外,也有报告支持在特定的场景下,标准IO要优于memory mapped file。

3. 对于非匿名memory mapping,如果文件被修改了,内存中的相应内容会被修改吗?

    不会。

4. 应用中如果需要大块的内存,使用malloc还是mmap?各有什么优缺点?

相关推荐