[Haskell-cafe] FFI and callbacks

John Goerzen jgoerzen at complete.org
Wed Jul 20 11:22:49 EDT 2005

On Wed, Jul 20, 2005 at 04:10:38PM +0100, Simon Marlow wrote:
> On 20 July 2005 14:35, John Goerzen wrote:
> > These systems generally have some sort of an opaque main loop,
> > implemented in C.  This loop would usually never return, or perhaps
> > only return once the UI is destroyed.
> Is the library thread-safe or not?  I mean OS-thread safe.  If it is,
> then you're home and dry: just compile your program with GHC's -threaded
> option, and any foreign calls that need to run concurrently with Haskell
> threads must be declared "safe" (which is the default in fact, so
> instead I should really advise you to mark all calls that don't need to
> run concurrently as "unsafe", because that's good for performance).

That's half of the question.  The other half is: what is the canonical
way of handling this mainloop that doesn't return from Haskell?  Do we
just treat it that way in Haskell as well, or would some people forkIO

Does any part of your answer vary depending on whether the Haskell
threads in question are forkIO threads or forkOS threads?  I imagine
that it might.

Unfortunately, the library I'm leaning towards packaging is not
thread-safe.  There is another library that is, but it is written in
C++, and making a Haskell binding for that is a little more than I have
the skills to do at the moment.

> If the library isn't thread-safe, then you're in the same boat as Gtk
> and wxHaskell (I believe) where there are known problems with having a
> multithreaded Haskell GUI app.  You can only have one OS thread (and
> hence only one Haskell thread) doing GUI operations, and that is the

What about multiple forkIO threads?

> thread in the main loop.  You have to somehow set up a communication
> between your other Haskell threads and the thread running the main loop
> - perhaps you can send requests of type (IO ()) down a channel to the
> main loop thread which wakes up occasionally to run them, for example.

I imagine there could be exceptions to this..  For instance, perhaps a
given operation needs to do 5 things, perhaps simultaneously, before
displaying a result.  It could, perhaps, fire off five threads and just
not display a result until all five have terminated, yes?


-- John

More information about the Haskell-Cafe mailing list