[Haskell-cafe] ForeignPtrs with liveness dependencies

Simon Marlow simonmar at microsoft.com
Wed Jul 27 05:57:29 EDT 2005

On 26 July 2005 16:49, Einar Karttunen wrote:

> "Simon Marlow" <simonmar at microsoft.com> writes:
>> No, unfortunately not.  You have foo's finalizer which refers to bar
>> via a touchForeignPtr.  If both foo and bar are unreachable
>> (references from finalizers don't count), then both foo and bar's
>> finalizers will be started together, and may run in any order.
> I didn't realize the "references from finalizers don't count" rule.

It does make sense.  If references from finalizers *did* keep objects
alive, then if you had two objects that referreed to each other by their
finalizers, neither would ever be finalized.

This paper has all the rationale, you might find it interesting:


Expressing ordering relationships between finalizers is known to be hard
- for instance, if you have a chain of N dependent finalizers that are
all unreachable, you don't want to take N major GCs to discover the
fact.  The canonical paper on this is Hans Boehm's "Destructors,
finalizers, and synchronization":


> What would happen if the finalizer of foo would resurrect bar after
> bar's finalizer has been run?

That can happen.  Nothing goes wrong on the Haskell side, but if this is
a problem for your C objects then you need to be aware of it.

>> So touchForeignPtr does only one thing: it expresses the precise
>> relationship "bar is alive if foo is alive".  If both are not alive,
>> then both finalizers can run, in any order.
> So reference counting the objects is the solution?

Perhaps.  It seems robust, anyway.

>> I realise this is very subtle.  By all means suggest improvements to
>> the docs.
> Mentioning that references from finalizers don't count could help
> someone not to repeat my mistakes.

Ok, will do.


More information about the Haskell-Cafe mailing list