-module(counter). -export([start/0, counter/0, next/0, set/1, stop/0]). -define(MAXCOUNT, 32767). start() -> register(?MODULE, spawn_link(?MODULE, counter, [])). counter() -> process_flag(trap_exit, true), count(0). count(N) when N > ?MAXCOUNT -> count(0); count(N) -> receive {next, FromPID} -> FromPID ! {next, N}, count(N+1); {set, New} -> count(New); {'EXIT', Pid, Reason} -> io:format("~p: ~p~n", [Pid, Reason]), exit(normal); {stop} -> exit(normal) end. set({present, N}) -> ?MODULE ! {set, N+1}. next() -> ?MODULE ! {next, self()}, receive {next, N} -> {present, N} end. stop() -> ?MODULE ! {stop}.