Processes, Messages and the Actor Model

Article · 4:00

Spawning, sending, receiving, carrying state in a loop, and the mailbox behaviour that will eventually bite you.

An Erlang process is not an operating system process and not a thread. It is a BEAM construct: around 300 words of memory to start, created in microseconds, scheduled by the VM rather than the kernel. A million of them on one machine is unremarkable. Each has its own heap and its own mailbox, and shares nothing with any other - when you send a message, the term is copied. That copying is the cost, and it is what buys the guarantee: no process can corrupt another's data, so a process that crashes cannot take anything else with it.

spawn/1 and spawn/3 start one and return a pid immediately, without waiting. Pid ! Message sends - asynchronously, never blocking, and it returns the message rather than any indication of delivery. Sending to a dead process is not an error; it succeeds and the message goes nowhere. That surprises everyone and it is deliberate: in a distributed system you cannot know whether a remote process is alive, so the language refuses to pretend.

receive ... end takes a message out of the mailbox. It matches patterns against messages in arrival order, taking the first that matches any clause, and blocks if none do. after Milliseconds -> adds a timeout, and after 0 -> checks without blocking.

State lives in the loop. With no mutable variables, a stateful process is a tail-recursive function that takes its state as an argument, receives a message, and calls itself with the new state. That is the whole pattern, and gen_server in phase three is this with the boilerplate removed.

Selective receive is the pitfall. If a message in the mailbox matches no clause, it stays there - and every subsequent receive scans past it. A process that receives one specific reply while ignoring everything else accumulates unmatched messages forever, and each scan gets slower because the mailbox is walked from the front. A process whose mailbox grows is the classic Erlang production failure, and the fix is to have a catch-all clause that at least logs and discards what you did not expect.

Registering a name with register/2 lets other processes reach a pid without being told it. Useful, and global mutable state - OTP gives you better options later.

-module(counter).
-export([start/0, increment/1, get/1, loop/1]).

%% ---------------- A stateful process is a tail-recursive loop ---------
start() ->
    spawn(?MODULE, loop, [0]).          % ?MODULE is this module's name

loop(Count) ->
    receive
        {increment, N} ->
            loop(Count + N);            % the new state, via the tail call

        {get, From} ->
            From ! {count, Count},      % reply by sending to the asker
            loop(Count);

        stop ->
            ok;                         % no recursive call: the process ends

        Other ->
            %% THE CLAUSE PEOPLE LEAVE OUT. Without it, anything
            %% unexpected stays in the mailbox for ever, every later
            %% receive scans past it, and the process slowly dies.
            io:format("counter: unexpected ~p~n", [Other]),
            loop(Count)
    end.

%% ---------------- A synchronous call, built by hand -------------------
increment(Pid) -> Pid ! {increment, 1}, ok.

get(Pid) ->
    Pid ! {get, self()},                % self() is my own pid
    receive
        {count, N} -> N
    after 5000 ->
        {error, timeout}                % ALWAYS have a timeout. Without
    end.                                % one this blocks for ever if the
                                        % other process died.

%% ---------------- In the shell ----------------
%%
%%   1> c(counter).
%%   2> P = counter:start().
%%   <0.86.0>                 % a pid: node, process id, serial
%%   3> counter:increment(P).
%%   4> counter:get(P).
%%   1
%%
%%   5> P ! anything.         % sending NEVER fails
%%   anything
%%   6> P ! stop.
%%   7> is_process_alive(P).
%%   false
%%   8> P ! hello.            % to a DEAD process. Still succeeds.
%%   hello                    % The message simply goes nowhere.
%%
%% That is not a bug. In a distributed system you cannot know whether a
%% remote process is alive, so the language does not pretend that you can.

%% ---------------- Mailbox mechanics ----------------
%%
%%   receive matches IN ARRIVAL ORDER, taking the first message that
%%   matches any clause. A message matching nothing stays put.
%%
%%   receive
%%       {specific, Reply} -> Reply      % only this
%%   end
%%
%%   Every other message queues up behind it for ever, and each later
%%   receive walks the queue from the front. A growing mailbox is THE
%%   classic Erlang production failure. Watch it with:
%%
%%   process_info(Pid, message_queue_len).
%%   erlang:process_info(Pid, [memory, message_queue_len, current_function]).

%% ---------------- Timeouts and non-blocking checks ----------------
%%
%%   receive X -> X after 1000 -> timeout end.   % wait up to a second
%%   receive X -> X after 0    -> empty   end.   % check, do not block
%%   receive after 5000 -> ok end.               % just sleep

%% ---------------- Registering a name ----------------
%%
%%   register(counter, P),
%%   counter ! {increment, 1},           % reachable without the pid
%%   whereis(counter).                   % the pid, or undefined
%%
%%   One name per node, and it is global mutable state. OTP gives you
%%   better ways to find a process; use this sparingly.

Discussion

No questions on this topic yet. Sign in to ask the first one.