Skip to content
Erlang

Ping-Pong Processes

Two processes pass messages back and forth using spawn and receive.

By EZ4Code Team
spawnsendreceiveconcurrency

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