-
Notifications
You must be signed in to change notification settings - Fork 0
/
ring.exs
66 lines (57 loc) · 1.43 KB
/
ring.exs
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
defmodule Ring do
@interval 2000
@name :ring
def start do
case :global.register_name(@name, self) do
:yes -> loop(self, :last, :ticking)
:no -> join
end
end
def join do
ring_pid = :global.whereis_name(@name)
send ring_pid, { :join, self }
loop ring_pid, :last, :tocking
end
def loop(ring_pid, :last, :ticking) do
receive do
{ :join, client_pid } ->
loop(ring_pid, client_pid, :ticking)
after
@interval ->
IO.puts "tick -> ringleader"
send ring_pid, { :tick }
loop(ring_pid, :last, :tocking)
end
end
def loop(ring_pid, :last, :tocking) do
receive do
{ :join, client_pid } ->
loop(ring_pid, client_pid, :tocking)
{ :tick } ->
IO.puts "tock"
loop(ring_pid, :last, :ticking)
end
end
def loop(ring_pid, next_pid, :ticking) do
receive do
{ :join, client_pid } ->
send next_pid, { :join, client_pid }
loop(ring_pid, next_pid, :ticking)
after
@interval ->
IO.puts "tick -> #{inspect next_pid}"
send next_pid, { :tick }
loop(ring_pid, next_pid, :tocking)
end
end
def loop(ring_pid, next_pid, :tocking) do
receive do
{ :join, client_pid } ->
send next_pid, { :join, client_pid }
loop(ring_pid, next_pid, :tocking)
{ :tick } ->
IO.puts "tock"
loop(ring_pid, next_pid, :ticking)
end
end
end