Alastair Reid alastair at
Thu Oct 3 03:44:18 EDT 2002

> To be honest, I don't understand why you are so opposed to this.

I don't want to encourage people to write code which can't work on
Hugs and NHC.  If we provide Haskell finalizers with the restriction
that they can only call C code, users will go ahead and write
finalizers which call arbitrary Haskell code and then the code won't
work with Hugs and NHC - portability is decreased. 

So, maybe we should make Haskell finalizers work as well on NHC and
Hugs as they do on GHC?  What would it take to do this?

I believe it would take a massive effort to make Haskell finalizers
work both for existing systems and new systems because:

1) Being able to write finalizers in Haskell is pointless
   unless they can safely modify shared state.  (Worse, it is
   dangerous because unsafely modifying shared state leads to 
   race conditions which are unbelievably hard to track down.
   Much harder than the debugging sessions that George envisages.)

   Any useful form of Haskell finalizer requires the provision of
   blocking synchronization which will require a complete rewrite of
   the runtime system and potentially decrease portability.

2) None of our Haskell primitives are intended for a multi-threaded
   environment.  Consider a pair of primitives that share a common
   data structure like hClose and open.  What happens if a finalizer
   calls hClose while the main thread is in the middle of creating a
   file?  It probably works ok but we know from experience with
   writing multithreaded code that the only way to be sure is to look
   at the code.

   In fact, we have to check it and every other Haskell primitive that
   affects some shared structure.  In other words, we have to vet a
   lot of code to see if it can be used in a single-threaded way and
   modify offending code by moving any allocations to the start or end
   of the modifications.

   We also have to keep this in mind every time we modify the 
   runtime system.

In short, we have to do most of the work of making Hugs support
preemptive concurrency: we have to provide blocking synchronization
and we have to rewrite our code as though a preemption could happen 
on any heap allocation.

Plus, it makes maintenance harder because it makes it easy to
introduce race conditions.

> Why not find out whether SimonM's patch works?  If it does, the
> problem is solved, we can use the nicer definition, and everybody is
> happy.

As you know, testing for race conditions is very hard.  We could test
and test and not see a problem and then a week into the release we get
a bug report.  But, worse, the report also says that the bug goes away
if they make some small change to their code.  The change will not
actually fix the problem, it will just change the allocation/GC
pattern so that the problem doesn't show up in the test.

Alastair Reid                 alastair at  
Reid Consulting (UK) Limited

More information about the FFI mailing list