[Haskell-cafe] Re: Problem with finalizers
Ivan Tomac
tomac at pacific.net.au
Tue May 15 09:06:19 EDT 2007
Hi Simon,
On 15/05/2007, at 8:31 PM, Simon Marlow wrote:
> There is no guarantee that a finalizer will be run before your
> program exits. The only thing you can be sure of is that it will
> *not* run while the ForeignPtr is still reachable by the garbage
> collector. In practice GHC will schedule the finalizer to run as
> soon as the GC detects that the ForeignPtr is unreachable. There
> will be a lag (possibly a very long lag) between the time at which
> the ForeignPtr becomes unreachable and the time at which a major GC
> is performed, and a further lag between the GC scheduling the
> finalizer and the finalizer actually being run. Furthermore, GHC
> will allow the program to exit without running all the outstanding
> finalizers, which is why your finalizer might not necessarily run.
>
What threw me off was the part in the GHC documentation for
newForeignPtr that states:
"The finaliser will be executed after the last reference to the
foreign object is dropped. Note that there is no guarantee on how
soon the finaliser is executed after the last reference was dropped;
this depends on the details of the Haskell storage manager. The only
guarantee is that the finaliser runs before the program terminates."
Section 5.5 of the FFI addendum has the same statement:
"There is no guarantee on how soon the finalizer is executed after
the last reference to the associated foreign pointer was dropped;
this depends on the details of the Haskell storage manager. The only
guarantee is that the finalizer runs before the program terminates."
I've tried running the test code under Hugs to see how a different
implementation of Haskell handles it but there were some
environmental problems when running ffihugs so I gave up on that for
now.
>> Is this normal and if so is it documented anywhere?
>
> It's documented in GHC's System.Mem.Weak module, which is used to
> implement ForeignPtrs in GHC. I'll add some documentation to
> ForeignPtr too.
Interesting. Thanks for the info.
>
>> Can this behavior be relied upon in future versions of GHC?
>
> You can rely on the lack of guarantees for as long as you like :-)
>
Heh, considering the question was a bit vague that's as good an
answer as any :)
What I meant was to ask for advice on whether it's better to just
manually clean up instead of relying on finalizers (and performGC/
yield).
Manually cleaning up handles feels a bit out of place in a language
like Haskell but I suppose it's better than having prettier code that
may or may not leak handles.
> Cheers,
> Simon
Ivan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20070515/8254a486/attachment.htm
More information about the Haskell-Cafe
mailing list