summaryrefslogtreecommitdiff
path: root/src/counter.erl
blob: 98605f661ee80c0f8c4d621a2d3248fd9a3bb64d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
-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}.