Threaded foreign functions calling back.

Wolfgang Thaller wolfgang.thaller at
Sat Sep 27 17:40:53 EDT 2003

Peter Strand wrote:

> Hi,
> I'd like to use a C-library which calls back into the haskell
> program, potentially from different threads at the same time.
> That is, the following calling sequence takes place:
>  (haskell) Calls C via foreign import.
>  (c)       Creates threads, which in turn calls back into
>            haskell via foreign exported functions.
> Is this supported in ghc?
> Some simple tests suggests that it does work, at least I don't
> get any crashes, if ghc is compiled with --enable-threaded-rts.
> But is this intended to work or am I just lucky?

Yes, this is indeed what --enable-threaded-rts is intended for. Beware 
that the code is not well-tested (that's why it's a separate option); 
however, there are no known bugs (if you encounter any, please tell 

You should also be aware of one remaining problem, which will be fixed 
in the upcoming GHC 6.2:Your C-library must not rely on the use of 
"thread-local state" (that is, pthread_key_create on unix and TlsAlloc 
on Win32); basically, when you call a foreign import, you don't know in 
what thread it will be executed (there's some interthread messaging and 
some black magic going on here). For the same reason, the value of 
errno cannot be reliably accessed from Haskell with GHC 6.0.
Most libraries are entirely unaffected by this problem, but I thought 
I'd warn you just in case.



More information about the Glasgow-haskell-users mailing list