Goroutines in Idris

A goroutine is a lightweight thread of execution.

module Main

import Data.List

f : String -> IO ()
f from = do
  mapM_ (\i => putStrLn (from ++ ": " ++ show i)) [0..2]

main : IO ()
main = do
  -- Running function f synchronously
  f "direct"

  -- Running function f concurrently
  forkIO (f "goroutine")

  -- Running an anonymous function concurrently
  forkIO (\=> putStrLn "going")

  -- Sleep to allow goroutines to complete
  sleep 1
  putStrLn "done"

Suppose we have a function call f(s). Here’s how we’d call that in the usual way, running it synchronously.

f "direct"

To invoke this function in a concurrent thread, use forkIO $ f s. This new thread will execute concurrently with the calling one.

forkIO (f "goroutine")

You can also start a concurrent thread for an anonymous function call.

forkIO (\=> putStrLn "going")

Our two function calls are running asynchronously in separate threads now. Wait for them to finish.

-- Sleep to allow goroutines to complete
sleep 1
putStrLn "done"

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 interleave because they are running concurrently.

$ runMain
direct : 0
direct : 1
direct : 2
goroutine : 0
going
goroutine : 1
goroutine : 2
done

Next we’ll look at a complement to concurrent threads in programming: channels.