[Haskell-cafe] ForeignPtrs with liveness dependencies

Einar Karttunen ekarttun at cs.helsinki.fi
Tue Jul 26 06:25:56 EDT 2005

"Simon Marlow" <simonmar at microsoft.com> writes:
> You might be able to find more information on this in the mailing list
> archives.  It's true that touchForeignPtr isn't enough to enforce an
> ordering on the running of finalizers, but it *can* be used to express a
> liveness relationship between one ForeignPtr and another (ForeignPtr A
> is alive if ForeignPtr B is alive).  This should be enough if you're
> dealing with pointer relationships between memory objects, for example,
> where it doesn't matter which one gets freed first when they're both
> unreferenced.

The order of the cleanup functions is significant in this case,
so that does not unfortunately help.

> If you really do need ordering, maybe it would be possible to use
> reference counting in your case?

I ended up using the following design, which seems to work fine:
data Foo = Foo (ForeignPtr Foo) (IORef [IO ()])
Each ForeignPtr Foo has a single finalizer which first calls the C-side
cleanup function for Foo and then executes all the IO-actions inside the 

Now the association becomes
associate (Foo _ ref) bar = 
  atomicModifyIORef ref (\lst -> (touchForeignPtr bar : lst, ()))

- Einar Karttunen

More information about the Haskell-Cafe mailing list