[Haskell-cafe] Bulletproof resource management

Jason Dagit dagit at codersbase.com
Fri Oct 8 13:19:37 EDT 2010

On Fri, Oct 8, 2010 at 9:39 AM, Florian Weimer <fw at deneb.enyo.de> wrote:
> At least in my experience, in order to get proper resource management
> for things like file or database handles, you need both a close
> operation and a finalizer registered with the garbage collector.  The
> former is needed so that you can create resources faster than the
> garbage collector freeing them.  The latter is a safety net in cases
> where proper resource management is not follwoed (perhaps in GHCi).
> When the explicit close operation or the finalizer has been invoked,
> the object must somehow be disabled, so that further operations on it
> fail (otherwise, you might dereference a dangling pointer).
> What's the idom for implementing this in Haskell (or GHC)?  It seems
> that a ForeignPtr cannot be written to (otherwise I'd change it to a
> null pointer when the resource is freed).  It's also not possible to
> check if the finalizers have been run.
> Can the finalizers hold a reference to the object which in turn holds
> the ForeignPtr to be finalized?  Or would that prevent the finalizers
> from running at all?  Is there a way to avoid the extra level of
> indirection (or is GHC sufficiently smart to optimize it away)?

Have you looked at the left-fold enumerator style?  It's what
takusen[1,2] and it's the basis for iteratees[3].

[1] http://projects.haskell.org/takusen/
[2] http://okmij.org/ftp/Haskell/#takusen
[3] http://okmij.org/ftp/Streams.html

I hope that gives you food for thought,

More information about the Haskell-Cafe mailing list