Alternatives to finalization

Manuel M T Chakravarty chak@cse.unsw.edu.au
Tue, 11 Mar 2003 09:30:50 +1100 (EST)


Nick Name <nick.name@inwind.it> wrote,

> 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.

You may want to have a look at how ports are closed by
finalizers in the Haskell Ports Library:

  http://www.cse.unsw.edu.au/~chak/haskell/ports/

It seems that the set up there is similar to yours.

Cheers,
Manuel