*gc-hook* is a system variable that allows a user function to be performed everytime garbage is collected [either explicitly with gc or automatically]. The default value for *gc-hook* is NIL. When *gc-hook* is set to a non-NIL symbol, it is enabled to execute the specified user routine. The user routine can be a quoted symbol or a closure. There are two parameters to the user routine, the total number of nodes and current free nodes after the garbage collection.
*gc-hook* ; returns NIL
(gc) ; returns NIL
(defun mygchook (&rest stuff) ; define the hook
(print stuff)
(print "my hook"))
(setq *gc-hook* 'mygchook) ; set up *GC-HOOK*
(gc) ; prints (2640 232)
; "my hook"
; returns NIL
(setq *gc-flag* T) ; turn on the system GC message
(gc) ; prints
; [ gc: total 2640, (2640 241)
; "my hook"
; 236 free ]
; returns NIL
(setq *gc-flag* NIL) ; turn off GC message
(setq *gc-hook* (lambda (x y) ; enable user routine
(princ "\007"))) ; that beeps at every GC
(gc) ; beeps
(defun expand-on-gc (total free) ; define EXPAND-ON-GC
(if (< (/ free 1.0 total) .1) ; IF free/total < .10
(progn (expand 2) ; THEN expand memory
(princ "\007")))) ; and beep
; NOTE: XLISP already gets more nodes
; automatically, this is just an example.
(setq *gc-hook* 'expand-on-gc) ; enable EXPAND-ON-GC
(gc) ; beeps when low on nodes
Note: The *gc-hook* and *gc-flag*
facilities can interact. If you do printing in the *gc-hook* user form and
enable
Note: The *gc-hook* user form is evaluated after the execution of the actual garbage collection code. This means that if the user form causes an error, it does not prevent a garbage collection.
Note: Since *gc-hook* is set to a symbol, the user defined form can be changed by doing another defun [or whatever] to the symbol in *gc-hook*. Note also that you should define the symbol first and then set *gc-hook* to the symbol. If you don't, an automatic garbage collection might occur before you set *gc-hook*, generating an error and stopping your program.
See the
*gc-hook*
system variable in the