-module(counter). -export([start/0, counter/0, next/0, set/1, stop/0]). -define(MAXCOUNT, 32767). start() -> register(counterPid, spawn_link(?MODULE, counter, [0])). 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}) -> counterPid ! {set, N}. next() -> counterPid ! {next, self()}, receive {next, N} -> {present, N} end. stop() -> counterPid ! {stop}.