gpt4 book ai didi

linux - Linux内存管理器中的"Weak reference"?

转载 作者:太空宇宙 更新时间:2023-11-04 11:28:50 28 4
gpt4 key购买 nike

在 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 输出中的 buffcache 与磁盘 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

好吧,我想知道更多关于我示例中的缓存是否可以反射(reflect)在 vmstat 输出的“缓存”列中。

最佳答案

确实没有一个好的方法来做到这一点——C 内存模型根本不允许 Java 内存模型允许的相同类型的行为。当与操作系统交互时,Java 的内存模型当然建立在 C 模型之上,这就是为什么 Java 堆必须由应用程序启动器手动限制的原因。

“buff”和“cache”列与内核使用的页面/磁盘缓存和内部缓冲区有关。这些缓存由内核自动处理 - 例如,读取文件会将内容放入“缓存”使用编号中,就像内存不足会将其提交到交换设备(“swpd”)一样。

关于linux - Linux内存管理器中的"Weak reference"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12632478/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com