Threads are subroutines that can run concurrently. Every Haskell program begins with one thread, called the main thread. Starting an additional thread is called forking a thread.

To fork a thread, use the forkIO function from the Control.Concurrent module.

Setting the output stream’s buffer mode to line-buffering will make the output of this example more readable.

We run f three times: Once in the main thread, and then twice in new forked threads.

At this point, our two forked threads are now running, and we wait for the user to press enter before ending the program; otherwise the main thread would end, thus terminating the program, before the other threads have time to finish.

The lines from f "main" are printed first; no fork has occurred yet.

Because f "forkA" and f "forkB" run concurrently, their putStrLn effects are interleaved.