typestar

spawn and send in Erlang

A process is cheap; ! sends, receive waits for a match.

%% A process is cheap; ! sends, receive waits for a match.
operator() ->
    receive
        {connect, From, Line} ->
            From ! {ok, Line},
            operator();
        hang_up ->
            ok
    end.

main(_) ->
    Pid = spawn(fun operator/0),
    Pid ! {connect, self(), 7},
    receive
        {ok, Line} -> io:format("Patched through line ~p~n", [Line])
    end,
    Pid ! hang_up,
    io:format("Board closed~n").

How it works

  1. spawn(fun operator/0) starts a process and answers its pid.
  2. Pid ! Message is fire-and-forget; self() names the sender.
  3. The operator loops by calling itself after each message.

Keywords and builtins used here

The run, in numbers

Lines
18
Characters to type
342
Tokens
100
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 100 seconds.

Type this snippet

Step 1 of 4 in Processes, step 25 of 31 in Language basics.

← Previous Next →