-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmath_server.erl
More file actions
68 lines (60 loc) · 1.32 KB
/
math_server.erl
File metadata and controls
68 lines (60 loc) · 1.32 KB
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
-module (math_server).
-compile([export_all]).
add(ServerPid, X, Y) ->
ServerPid ! {add, X, Y, self()},
receive
{result, Result} ->
Result
after 100 ->
{error, timeout}
end.
sub(ServerPid, X, Y) ->
ServerPid ! {subtract, X, Y, self()},
receive
{result, Result} ->
Result
after 100 ->
{error, timeout}
end.
init() ->
%% startup
spawn(fun() -> loop(dict:new()) end).
loop(State) ->
Response = receive
stop ->
stop(State),
ok;
{add, X, Y, Caller} ->
{compute_add(X, Y, State), Caller};
{subtract, X, Y, Caller} ->
{compute_subtract(X, Y, State), Caller}
end,
case Response of
ok ->
ok;
{{result, Result, Cache}, NewCaller} ->
NewCaller ! {result, Result},
loop(Cache)
end.
stop(_State) ->
%% cleanup
ok.
shutdown(ServerPid) ->
ServerPid ! stop,
ok.
compute_add(X, Y, Cache) ->
case dict:find({X, Y, add}, Cache) of
error ->
Result = X + Y,
{result, Result, dict:store({X, Y, add}, Result, Cache)};
{ok, Result} ->
{result, Result, Cache}
end.
compute_subtract(X, Y, Cache) ->
case dict:find({X, Y, sub}, Cache) of
error ->
Result = X - Y,
{result, Result, dict:store({X, Y, sub}, Result, Cache)};
{ok, Result} ->
{result, Result, Cache}
end.