12.8 Garbage collection. 4tH 4tH Forth compiler
Реклама
Реклама
CHAPTER 12. STANDARD LIBRARIES
12.8
Garbage collection
174
4tH features a simple form of garbage collection. The only thing between ”real” garbage collection and this implementation is that you remain in control at all times. First you have to decide what kind of datatype you want to put under control of the garbage collector by defining a pragma. This will enable cell garbage collection:
[pragma] forcecellgc include lib/gc.4th
If you don’t define this pragma, garbage collection will default to characters. Since the garbage collector uses the same libraries we discussed in section 12.7, you can size them with ”/HEAP”. Next, you have to start garbage collection: start-gc
It’s time to start a ”scope”: start-scope >r
This will return a single cell scope token which is used to keep track of when to do garbage collection. Now the fun starts: allocate and resize away all you like, but instead of using the usual allocation words, you use these:
50 gc-alloc >r s" Hello temporary world!" r@ place r@ count type cr r> 100 gc-resize count type cr
\ Now store the string
\ Let’s print the string
\ Here is your string again
Wow, did you see that?! We lost a pointer in the last line! Well, that isn’t too bad in this case - we’re using a garbage collector after all. Note you may open up new scopes if you like, but you have to close them in the right order, so you may want to use the data stack to keep track of your scope tokens, like we did.
Closing a scope is easy. Just pass the scope token to ”END-SCOPE” and all memory you allocated since the last ”START-SCOPE” will be automatically freed: r> end-scope
When you’ve ended a scope, the garbage collection will automatically revert to the previous scope, so any allocation you do after closing a scope will be handled by the previous scope.
Finally, when you’re done you can shutdown the entire garbage collector by issuing: end-gc
This will free up all garbage collection support structures, which are also dynamically allocated. Famous last words: do not free or resize memory allocated with ”GC- ALLOC” or ”GC-RESIZE” with the standard words ”FREE” or ”RESIZE”. Ignore this warning at your own peril.
Изтегляне
Реклама