Alternatives to finalization

Nick Name nick.name@inwind.it
Mon, 10 Mar 2003 00:59:00 +0100


As the result of a conversation on haskell-gui, I have tried to
implement the disallocation of resources when a stream is garbage
collected.

To explain myself:

I have a function

f :: IO [a]

which returns a lazy stream after allocating some resource to feed it
(say installing a callback).

I wish that the resource could be disallocated when it's no longer used.
I did the obvious implementation with Weak.addFinalizer; results are
encouraging but not completely satisfying; the scheme I used is:

f = do
    allocateResource
    l <- makeTheStream
    addFinalizer l (disallocateResource)
    return l

The problem is that if no memory is allocated, no garbage collection
happens; of course finalization is not guaranteed, as the manual states.

Another alternative is to make f return an esplicit "close stream"
action:

f :: IO ([a],IO ())

Is anyone willing to explain me other alternatives if there are, or to
tell me that there aren't?

Thanks for attention

Vincenzo