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
Setting the output stream’s buffer mode to line-buffering will make the output of this example more readable.
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.
task "forkA" and
task "forkB" run concurrently, their
putStrLn effects are interleaved.