【发布时间】:2012-09-28 01:40:45
【问题描述】:
在 Java 中,如果内存用完,弱引用会被垃圾回收。在 Linux 中,malloc() 总是返回一个强引用,即。在调用者调用free() 函数之前,指针永远不会被释放。
我想为缓存分配一个缓冲区,当内存用完时可以自动释放,如下所示:
cache_t cache;
if (! cache_alloc(&cache))
die("Memory out");
cache_lock(&cache); // realloc cache mem if it is collected
if (! cache->user_init) { // The "user_init" maybe reset if the cache mem is collected
// lazy-init the cache...
load_contents(cache->mem, ...);
cache->user_init = 1;
}
// do with cache..
stuff_t *stuff = (stuff_t *) cache->mem;
...
cache_unlock(&cache);
vmstat 的输出中的 buff 和 cache 似乎与磁盘 IO 相关:
$ vmstat
procs -----------memory---------- ---swap-- -----io---- -system-- ----cpu----
r b swpd free buff cache si so bi bo in cs us sy id wa
0 0 51604 554220 13384 314852 3 10 411 420 702 1063 8 3 75 14
好吧,我想了解更多关于我的示例中的缓存是否可以反映在 vmstat 输出的“缓存”列中。
【问题讨论】:
-
操作系统通过 MMU、分页等为你做这件事。那何必呢?
-
@Vlad:我不明白..你能详细解释一下吗?
-
@VladLazarenko 我认为 OP 是在谈论虚拟地址空间耗尽,而不是物理内存。操作系统没有解决前者。
标签: linux caching memory-management weak-references