Bound Threads

Wolfgang Thaller wolfgang.thaller at gmx.net
Fri Mar 14 07:47:59 EST 2003


> In general, I think that only the programmer knows what strategy to 
> use.

Do programmers know? I know about my own program, but do I know about 
the library that I am going to use? Does it use forkOS or forkIO? What 
will be the consequences if it uses forkIO and I do a lengthy foreign 
call?
Does the library writer know about my program?
I fear I'll end up wrapping every call to *Haskell* libraries in your 
"threadSafe" combinator - just to be sure that the library and my 
program don't interfere.
I'm very afraid of having some long debugging sessions once we have 
this "feature".

> Now, I have an example from the wxHaskell GUI library that exposes some
> of the problems with multiple threads. I can't say it can be solved
> nicely with forkOS, so I wonder how it would work out with 
> "threadsafe":

In both cases, threadsafe and forkOS, we would have two OS threads, and 
we would have OS thread context switches between them. So it will get 
us nowhere to count the OS thread context switches involved 
(incidentally, handling GUI events is an area where we can easily 
afford the cost of OS thread context switches).

You would mark the call to the wxWindows event loop as threadsafe 
(actually, in the CVS version of GHC, "safe" is currently a shorthand 
for "threadsafe" as nobody has yet provided a logically sound and 
meaningful definition of the semantics that "safe" should have instead).
In case that wxWindows makes the assumption that it's functions are 
invoked _from the same OS thread_ that it used to call your callback, 
you can add "bound" to the foreign export statement for your callback.

Then you would use just forkIO and everything would work.

(If wxWindows doesn't allow access from multiple threads, then of 
course you can't call wx functions from the thread you just forked. But 
that's the same no matter which proposal we follow.)

> The problem is that the "processor" thread won't run since we have 
> returned
> to C-land and the haskell scheduler can't run.

Threadsafe means that you don't need to care about things like that.

> [...] but it is how it is done in all other major programming 
> languages.

Only other languages don't require you to manually keep track of a 
correspondence between lightweight and heavyweight threads.

> Since the haskell function is called via a callback, I guess that 
> "threadsafe"
> should also apply to "wrapper" functions -- that is, when the foreign 
> world
> calls haskell, we use another OS thread to run the haskell code.

Sorry, no clue what you mean... could you elaborate? "threadsafe" just 
applies to imports, not to exports and wrappers. "bound" applies to 
exports and wrappers, but not to imports. Should it be different?

Cheers,

Wolfgang




More information about the FFI mailing list