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
spawn(fun operator/0)starts a process and answers its pid.Pid ! Messageis fire-and-forget;self()names the sender.- The operator loops by calling itself after each message.
Keywords and builtins used here
endformatfunmainoperatorreceivespawn
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.
Step 1 of 4 in Processes, step 25 of 31 in Language basics.