我为 Postscript 虚拟机编写了一个简单的垃圾收集器,并且我很难设计一套合适的规则来确定何时进行收集(当空闲列表太短时?)以及何时分配新空间(当有很多空间可以使用吗?)。
到目前为止我都是自底向上写的,但是这个问题涉及到顶层设计。所以我觉得我的立场不稳固。
所有对象都受到管理,并且只能通过运算符函数进行访问,因此这是 C 中的收集器,而不是 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#