-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver_process.ex
69 lines (56 loc) · 1.36 KB
/
server_process.ex
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
defmodule ServerProcess do
def start(callback_module) do
spawn(fn ->
initial_state = callback_module.init
loop(callback_module, initial_state)
end)
end
def cast(server_pid, request) do
send(server_pid, {:cast, request})
end
def call(server_pid, request) do
send(server_pid, {:call, request, self()})
receive do
{:response, response} -> response
end
end
defp loop(callback_module, current_state) do
receive do
{:call, request, caller} ->
{response, new_state} = callback_module.handle_call(
request,
current_state
)
send(caller, {:response, response})
{:cast, request} ->
new_state = callback_module.handle_cast(
request,
current_state
)
loop(callback_module, new_state)
end
end
end
defmodule KeyValueStore do
def start do
ServerProcess.start(KeyValueStore)
end
def put(pid, key, value) do
ServerProcess.cast(pid, {:put, key, value})
end
def get(pid, key) do
ServerProcess.call(pid, {:get, key})
end
def init do
%{}
end
def handle_cast({:put, key, value}, state) do
Map.put(state, key, value)
end
def handle_call({:put, key, value}, state) do
{:ok, Map.put(state, key, value)}
end
def handle_call({:get, key}, state) do
{Map.get(state, key), state}
end
end