addForeignPtrFinalizer - finalizers run in FIFO or LIFO order?

Henning Thielemann lemming at
Fri Aug 17 18:32:14 CEST 2012

On Fri, 17 Aug 2012, Henning Thielemann wrote:

> On Fri, 17 Aug 2012, Henning Thielemann wrote:
>> The doc of base-4.5:Foreign.ForeignPtr.addForeignPtrFinalizer states:
>>   "This function adds a finalizer to the given foreign object. The 
>> finalizer will run before all other finalizers for the same object which 
>> have already been registered."
>> I do
>>  addForeignPtrFinalizer finalize1 fp
>>  addForeignPtrFinalizer finalize2 fp
>> and let the finalizers print something when they are started.
>> I get the output:
>>  finalizer1
>>  finalizer2
>> This indicates that the newly added finalizer is run _after_ the finalizers 
>> that are already registered. Is this a documentation bug or a bug in the 
>> base library?
> Hm, it seems to depend on the context. In some situations I get the correct 
> (reversed) order
>  finalizer2
>  finalizer1
> and in others I get finalizer1 first and then finalizer2. Any hint what can 
> change the order of finalizers?

continuing my monologue ...

It seems that a simple modification like turning a not directly related 
allocaBytes into a mallocBytes reverses the order from incorrect to 
correct (reversed). Maybe adding the finalizers is not the problem but 
running them. Maybe there are different ways to run the finalizers and 
allocaBytes causes an invalid execution of finalizers whereas mallocBytes 
leaves the correct way.

More information about the FFI mailing list