[Haskell] Re: Safe forking question
simonmarhaskell at gmail.com
Mon Dec 4 05:35:07 EST 2006
Chris Kuklewicz wrote:
> In response to question by Cat Dancer <cat at catdancer.ws> I wrote a few tests of
> sending asynchronous signal to a thread using GHC 6.6
> The goal was to run a child thread via forkIO and use handle or finally to respond
> to the thread's demise.
> Unfortunately, it seems that there is an irreducible window where this fails. The
> forkIO returns but any exception handlers such as block/handle/catch/finally are
> not in place yet.
We might consider it a bug that a new thread is started in "async exceptions
unblocked" mode. It's true that this does mean there's no way to reliably start
a thread and guarantee to know if it is killed.
Starting threads in 'blocked' mode isn't the answer. That would force everyone
to add an 'unblock' to their forkIO's after setting up an exception handler, and
that's too easy to forget (and not backwards compatible). So instead we could
introduce a new abstraction:
forkCatchIO :: (Exception -> IO ()) -> IO () -> IO ThreadId
which combines forkIO with catch in an atomic way, such that the handler is
guaranteed to execute if the thread receives an exception. You can implement
this using an MVar and not returning the ThreadId until the child thread is
inside the exception handler (as in your example): this is ok because the only
way a thread can receive an exception is by knowing its ThreadId. However it's
less than perfect in performance terms; if we had a primitive fork that created
a thread in blocked mode we could do much better.
If there's some agreement that this is the way to go, I'll file a task for GHC
and try to get to it before 6.8.
More information about the Haskell