Ping-Pong Processes
Two processes pass messages back and forth using spawn and receive.
Code
-module(pingpong).
-export([start/1]).
start(N) ->
Pong = spawn(fun() -> pong() end),
Ping = spawn(fun() -> ping(N, Pong) end),
ok.
ping(0, _Pong) ->
io:format("ping done~n");
ping(N, Pong) ->
Pong ! {ping, self()},
receive
pong -> io:format("ping received pong~n")
end,
ping(N - 1, Pong).
pong() ->
receive
{ping, From} ->
io:format("pong received ping~n"),
From ! pong,
pong();
stop ->
ok
end.
% Usage: pingpong:start(3).Explanation
This is the canonical Erlang concurrency example. spawn/1 creates a new BEAM process that runs the given fun. The ping process sends {ping, self()} to pong and waits for a pong reply; pong loops, replying to each ping. Processes share no memory — all state flows through messages. The pong/0 function uses tail recursion to 'loop forever' without growing the stack.
More Erlang Snippets
gen_server Counter
Build a stateful server with the gen_server behaviour.
Supervisor Tree
Define a supervisor that starts workers and restarts them on crash.
Selective Receive with References
Match a specific reply out of many messages using a unique reference.
Links, Exit Trapping & 'Let It Crash'
Use link and trap_exit to detect process death and recover.
Stateful Server via Tail Recursion
Hold mutable state in a process by threading it through recursive calls.
Parallel Map with rpc:pmap
Apply a function to each list element in parallel across processes.