【发布时间】:2013-02-04 18:33:04
【问题描述】:
假设我想对一个可能非常大的文件执行顺序写入。
如果我 mmap() 一个巨大的区域并在整个区域上进行 madvise(MADV_SEQUENTIAL),那么我可以以相对有效的方式写入内存。我已经可以正常工作了。
现在,为了在我编写时释放各种操作系统资源,我偶尔会在已写入的小块内存上执行 munmap()。我担心 munmap() 和 msync() 会阻塞我的线程,等待数据物理提交到磁盘。我一点都不能放慢我的写作速度,所以我需要另辟蹊径。
在已经写入的小块内存上使用 madvise(MADV_DONTNEED) 会更好吗?我想告诉操作系统将内存延迟写入磁盘,而不是阻塞我的调用线程。
madvise() 的手册页有这样的说法,这是相当模棱两可的:
MADV_DONTNEED
Do not expect access in the near future. (For the time being, the
application is finished with the given range, so the kernel can free
resources associated with it.) Subsequent accesses of pages in this
range will succeed, but will result either in re-loading of the memory
contents from the underlying mapped file (see mmap(2)) or
zero-fill-on-demand pages for mappings without an underlying file.
【问题讨论】:
-
我不会尝试这个;文件映射上的
MADV_DONTNEED可能被解释为您希望操作系统丢弃对文件的更改。 -
@Zack,你有关于 MADV_DONTNEED 放弃对文件的更改的参考吗?
-
@antonm man7.org/tlpi/code/online/dist/vmem/madvise_dontneed.c.html 有一个演示它的程序(不幸的是,它不是独立的,但很容易修改)。另请参阅gnu.org/software/libc/manual/html_node/…(“
MADV_DONTNEED:不再需要该区域。内核可能会释放这些页面,导致对页面的任何更改丢失”(强调我的))和这个 LKML 2005 年的主题:lkml.org/lkml/2005/6/28/188 .
标签: linux linux-kernel kernel shared-memory mmap