summaryrefslogtreecommitdiff
path: root/src/counter.erl
blob: b46503ed8b30f80c14d390d8b897ac2de9b4fce5 (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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
-module(counter).
-behaviour(gen_server).
-define(SERVER, ?MODULE).

-export([start_link/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
	 terminate/2, code_change/3]).

-export([start/0, counter/0, next/0, set/1, stop/0]).

-define(MAXCOUNT, 32767).

start_link() ->
	gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).

init(_Args) ->
	{ok, 0}.

handle_call(_Request, _From, State) ->
	{reply, ok, State}.

handle_cast(_Msg, State) ->
	{noreply, State}.

handle_info(_Info, State) ->
	{noreply, State}.

terminate(_Reason, _State) ->
	ok.

code_change(_OldVsn, State, _Extra) ->
	{ok, State}.

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

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}.