Goroutines in Elixir

A goroutine is a lightweight thread of execution.

defmodule Example do
  def f(from) do
    for i <- 0..2 do
      IO.puts("#{from} : #{i}")
    end
  end

  def main do
    # 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 process, use `spawn/1`.
    # This new process will execute concurrently with the calling one.
    spawn(fn -> f("process") end)

    # You can also start a process for an anonymous function call.
    spawn(fn -> IO.puts("going") end)

    # Our two function calls are running asynchronously in
    # separate processes now. Wait for them to finish
    # (simulating using a sleep here; for a more robust approach,
    # use a mechanism like GenServer or Task).
    :timer.sleep(1000)
    IO.puts("done")
  end
end

To run this program, just call the main function in the Example module as follows:

Example.main()

When we run this program, we see the output of the blocking call first, then the output of the two processes. The processes’ output may be interleaved because processes are being run concurrently by the Elixir runtime.

direct : 0
direct : 1
direct : 2
process : 0
going
process : 1
process : 2
done

Next, we’ll look at a complement to concurrent processes in Elixir programs: message passing and processes communication.