Bound Threads

Wolfgang Thaller wolfgang.thaller at gmx.net
Fri Mar 7 10:10:27 EST 2003


Alastair Reid wrote:

>
>> Does anyone plan to add support for multiple OS threads to Hugs or 
>> NHC?
>
> I think it will depend a bit on the complexity so let me sketch how I
> think it can be implemented.
>
> First let me outline my current understanding of what 'bound' means.
> Consider the following scenario:
>
>   Haskell program is running in OS thread 't1'
>   Haskell program calls C function 'foo'.
>   'foo' forks a new OS thread 't2'.
>   In parallel: 't1' calls Haskell function 'f1' and
>                't2' calls Haskell function 'f2'
>   'f1' calls C function 'g1'
>   'f2' calls C function 'g2'

> My understanding is that 'bound' requires that 'g1' be executed by
> thread 't1' and that 'g2' be executed by thread 't2'.  It would be
> nice if 'f1' and 'f2' could run simultaneously but the ffi is not
> going to impose that on us.  If 'f1' were to block on an MVar, 'f2'
> could start running and vice-versa.  While 'g1' is running, 'f2' can
> run and while 'g2' is running, 'f1' can run.

Yes, if the Haskell functions 'f1' and 'f2' are both exported using 
"bound", that is

foreign export bound "f1" f1 :: something
foreign export bound "f2" f2 :: something


> Based on this understanding, I believe that single-threaded runtimes
> could easily implement 'bound' by doing nothing more than using a lock
> to ensure that at most one OS thread executes Haskell code at once.

That was the general intention.

Things might get more complex though if you want non-blocking foreign 
calls (a.k.a. "threadsafe"). Then you could either always create one OS 
thread for every Haskell thread, or use a slightly more complex scheme 
(as GHC does, but I'm sure there are other ways of doing this). 
Implementing "threadsafe" is basically independent from implementing 
the bound threads proposal, i.e. you can implement one without 
implementing the other (GHC currently has "threadsafe", but "bound 
threads" are still science fiction).

Cheers,

Wolfgang




More information about the FFI mailing list