Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between forkIO/forkOS and forkProcess?

Tags:

haskell

I'm not sure what the difference between forkIO/forkOS and forkProcess are in Haskell. To my understanding, forkIO/forkOS are more like threads (analogous to pthread_create in C) whereas forkProcess starts a separate process (analogous to fork).

like image 879
Aneesh Durg Avatar asked Jan 05 '17 12:01

Aneesh Durg


2 Answers

forkIO creates a lightweight unbound green thread. Green threads have very little overhead; the GHC runtime is capable of efficiently multiplexing millions of green threads over a small pool of OS worker threads. A green thread may live on more than one OS thread over its lifetime.

forkOS creates a bound thread: a green thread for which FFI calls are guaranteed to take place on a single fixed OS thread. Bound threads are typically used when interacting with C libraries which use thread-local data and expect all API calls to come from the same thread. From the paper specifying GHC's bound threads:

The idea is that each bound Haskell thread has a dedicated associated OS thread. It is guaranteed that any FFI calls made by a bound Haskell thread are made by its associated OS thread, although pure-Haskell execution can, of course, be carried out by any OS thread. A group of foreign calls can thus be guaranteed to be carried out by the same OS thread if they are all performed in a single bound Haskell thread.

[...]

[F]or each OS thread, there is at most a single bound Haskell thread.

Note that the above quotation does not exclude the possibility that an OS thread associated with a bound thread can act as a worker for unbound Haskell threads. Nor does it guarantee that the bound thread's non-FFI code will execute on any particular thread.

forkProcess creates a new process, just like fork on UNIX.

like image 110
Benjamin Hodgson Avatar answered Oct 04 '22 12:10

Benjamin Hodgson


forkIO creates a lightweight thread managed by Haskell's runtime system. It is unbound, i.e. it can be ran by any OS thread.

forkOS creates a bound thread, meaning it is bound to an actual OS thread. This can be necessary when using C functions for example.

forkProcess forks the current process like fork() in C.

like image 31
tomferon Avatar answered Oct 04 '22 12:10

tomferon