20,741
edits
m (→Problem) |
m (→Mark/Sweep) |
||
| Line 17: | Line 17: | ||
The mark-and-sweep algorithm consists of two phases: In the first phase, it finds and marks all accessible objects. The first phase is called the mark phase. In the second phase, the garbage collection algorithm scans through the heap and reclaims all the unmarked objects. The second phase is called the sweep phase. | The mark-and-sweep algorithm consists of two phases: In the first phase, it finds and marks all accessible objects. The first phase is called the mark phase. In the second phase, the garbage collection algorithm scans through the heap and reclaims all the unmarked objects. The second phase is called the sweep phase. | ||
The mark/sweep algorithm can also be easily expressed in Nasal tself: | |||
<syntaxhighlight lang="php"> | |||
var garbageCollect = func (roots) { | |||
foreach(var root; roots) { | |||
mark(root); | |||
} | |||
sweep(); | |||
} | |||
</syntaxhighlight> | |||
The mark() function would just recursively check (i.e. calling itself) if the "marked" flag is set or not, and make sure to set the mark bit for all referenced objects: | |||
<syntaxhighlight lang="php"> | |||
var mark = func (obj) { | |||
if (!p.marked) { | |||
foreach( var referenced; referenced_by(obj) ) | |||
mark(referenced); | |||
} | |||
} | |||
</syntaxhighlight> | |||
Finally, the sweep() function (reap() in the Nasal GC), will free all unreachable objects and reclaim the memory: | |||
<syntaxhighlight lang="php"> | |||
var sweep = func { | |||
foreach(var obj; allocated_objects) { | |||
if (obj.marked) obj.marked=0; | |||
else reclaim(obj); | |||
} | |||
} | |||
</syntaxhighlight> | |||
= Objective = | = Objective = | ||