[Haskell-cafe] Re: Problem with finalizers

Simon Marlow simonmarhaskell at gmail.com
Tue May 15 06:31:09 EDT 2007


Ivan Tomac wrote:
> It appears that if I add
> 
> import Control.Concurrent
> 
> and call yield just after performGC then the finalizer does get called.
> But it only seems to work if I call both performGC and yield and in that 
> order.

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.

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

> 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 :-)

Cheers,
	Simon


More information about the Haskell-Cafe mailing list