Goroutines in Erlang

A lightweight thread of execution in Erlang is known as a process. Here’s how you can accomplish similar functionality to goroutines using Erlang.

Explanation and Code Example

A lightweight thread of execution

An Erlang process is a lightweight thread of execution.

-module(goroutines).
-export([start/0, f/1]).

f(From) ->
    loop(From, 0).

loop(From, 3) ->
    ok;
loop(From, N) ->
    io:format("~s : ~p~n", [From, N]),
    loop(From, N + 1).

start() ->
    % Synchronously call the function
    f("direct"),

    % Start a new process to call the function concurrently
    spawn(fun() -> f("process") end),

    % Start a new process to call an anonymous function concurrently
    spawn(fun() -> io:format("going~n") end),

    % Sleep to ensure the started processes have time to complete
    timer:sleep(1000),
    io:format("done~n").

Detailed Explanation

  • Function Definition: We define an Erlang module goroutines and export two functions start/0 and f/1.

  • Loop Function: The function f/1 calls a helper function loop/2, iterating 3 times and printing a message each time.

  • Start Function: The start/0 function demonstrates synchronous call and the concurrent process creation:

    • Call f("direct") synchronously.
    • Use spawn/1 to create a new process to call f("process"), enabling concurrent execution.
    • Use spawn/1 to start another process with an anonymous function, printing “going”.
    • Use timer:sleep(1000) to wait for the processes to finish.

Running the Program

To run the program and see the output:

$ erl -noshell -s goroutines start -s init stop

Expect to see output similar to:

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

In this example, the spawn/1 function is used to create new concurrent processes, which is how we achieve the concurrency seen with goroutines.