I would like to run some code when something is garbage-collected. Fine, he says, just the job for finalizers (module Weak). Unfortunately, they don't seem to offer a general solution, as the code below demonstrates (presumably, smallish things are copied, not shared, so that the finalizers run too early?). Is there a general way to add finalizers to values of arbitrary type (and have them run when the value, not just one copy of it, disappears)? Or is this behaviour -he hopes- a bug, to be fixed in the next release? Claus ------------- session Main> y nothing is 0 Main> x nothings are (0,0) Main> runAllFinalizers nothing was Main> y 0 Main> x (0,0) ------------- program import IOExts import Weak y = unsafePerformIO $ do { x<-return 0 ; putStrLn "nothing is" ; addFinalizer x (putStrLn "nothing was") ; return x } x = unsafePerformIO $ do { x<-return (0,0) ; putStrLn "nothings are" ; addFinalizer x (putStrLn "nothings were") ; return x }
I would like to run some code when something is garbage-collected. Fine, he says, just the job for finalizers (module Weak). Unfortunately, they don't seem to offer a general solution, as the code below demonstrates (presumably, smallish things are copied, not shared, so that the finalizers run too early?).
Yes, small Ints (approximately 30 bits worth) and Chars have a special representation which makes it impossible to tell if they have been GC'd GHC has a similar problem for Chars and small ints (-15..15 I think).
Is there a general way to add finalizers to values of arbitrary type (and have them run when the value, not just one copy of it, disappears)?
No. Anything that is represented as an Int or Char on the heap could behave this way. (The unit value "()", occurences of [], etc may behave the same way.) The only fix is to wrap the object in a data constructor.
Or is this behaviour -he hopes- a bug, to be fixed in the next release?
Bug? Probably Likely to be fixed anytime soon? I hesitate to speak for the current maintainers but, since it is caused by a fundamental part of Hugs' implementation, I wouldn't hold my breath waiting for a fix.
participants (2)
-
Alastair Reid -
C.Reinke