【发布时间】:2011-09-16 01:10:35
【问题描述】:
我已经为 Postscript 虚拟机编写了一个简单的垃圾收集器,但我很难为何时进行收集(空闲列表太短时?)以及何时分配新的空间(当有很多空间可以使用时?)。
到目前为止,我都是自底向上写的,但是这个问题涉及到顶层设计。所以我觉得我在摇摇欲坠的基础上。 所有对象都被管理并且只能通过操作符函数访问,所以这是一个收集器in C,而不是for C。
主分配器函数称为gballoc:
unsigned gballoc(mfile *mem, unsigned sz) {
unsigned z = adrent(mem, FREE);
unsigned e;
memcpy(&e, mem->base+z, sizeof(e));
while (e) {
if (szent(mem,e) >= sz) {
memcpy(mem->base+z, mem->base+adrent(mem,e), sizeof(unsigned));
return e;
}
z = adrent(mem,e);
memcpy(&e, mem->base+z, sizeof(e));
}
return mtalloc(mem, 0, sz);
}
在不知道所有类型和函数的含义的情况下,我确定这是胡言乱语,所以这里是同一函数的伪代码:
gballoc
load free list head into ptr
while ptr is not NULL
if free element size is large enough
return element, removed from list
next ptr
fallback to allocating new space
所以这是一个简单的“首次拟合”算法,没有雕刻(但分配会保留它们的大小;因此,为小对象重用的大空间可以在以后再次为大对象重用)。
但是我什么时候应该打电话给collect()?
编辑: 其余代码和相关模块已发布在 comp.lang.postscript 中,在线程中: http://groups.google.com/group/comp.lang.postscript/browse_thread/thread/56c1734709ee33f1#
【问题讨论】:
标签: c garbage-collection dynamic-memory-allocation