FFI, safe vs unsafe

Simon Marlow simonmar at microsoft.com
Wed Mar 29 10:11:56 EST 2006

On 29 March 2006 14:35, John Meacham wrote:

> On Wed, Mar 29, 2006 at 02:05:35PM +0100, Simon Marlow wrote:
>> What you are suggesting is that there may be implementations that do
>> not support reentrant/blockable, but do support the others.  And in
>> that case, of course you really need to know the difference between
>> blockable and reentrant.  I'm just not sure the standard should
>> allow such implementations.
> It would be a very odd thing to disallow, seeing as how it would rule
> out or at least place fairly large implementation restrictions on
> yhc,hugs and jhc and not a single foreign import in the standard
> libraries needs to be 'blockable reentrant' as far as I can tell.
> though, I do need to look at hugs and yhcs source more carefully to
> know whether that is the case for sure. it depends on a lot of
> implementation details and how they handle OS-level threads and
> blockable in general. 

Ok, let's explore how difficult it really is.

Take a single-threaded implementation that forks OS threads for
concurrent foreign calls.  Let's call the OS thread running Haskell code
the "runtime thread".  An OS thread wanting to call a foreign export
must make an RPC to the runtime thread.  You could do this by:

  - have a channel for RPC requests

  - the callee creates a condition var for the result, and sends
    the call details down the channel with the condition var.

  - the runtime thread picks up the request in its event loop and
    forks a Haskell thread to handle it

  - when the Haskell thread completes it places the result in the
    right place and signals the condition variable

  - the callee picks up the result, frees the resources and continues
    on its merry way

can't be more than a couple of days work, unless I'm missing something?
It's not particularly fast, but then call-ins in GHC aren't fast either.


More information about the Haskell-prime mailing list