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.

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

We define a function called task, which:

  1. Increments the taskCompleted variable.

We run task 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 do not want the main thread to end (thus terminating the program) before the other threads have time to finish. So we wait until the value of tasksCompleted reaches 3.

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

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

The interleaving is nondeterministic; if you run this program multiple times, you may see different orderings.