Goroutines in Haskell
Our example demonstrates the use of lightweight threads of execution. Here’s the full source code in Haskell:
Suppose we have a function call f(s)
. Here’s how we’d call that in the usual way, running it synchronously.
To invoke this function in a concurrent thread, use forkIO $ f(s)
. This new thread will execute concurrently with the calling one.
You can also start a concurrent thread for an anonymous function call.
Our two function calls are running asynchronously in separate threads now. We wait for them to finish. (For a more robust approach, use a synchronization primitive like MVar
or Chan
).
When we run this program, we see the output of the blocking call first, then the output of the two concurrent threads. The threads’ output may be interleaved, because threads are being run concurrently by the Haskell runtime.
Next, we’ll look at a complement to concurrent threads in Haskell programs: channels.