-
Notifications
You must be signed in to change notification settings - Fork 0
/
exgreat.exs
83 lines (74 loc) · 1.89 KB
/
exgreat.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
defmodule Great do
def sendSidewards(left, right) do
receive do
{:left, num} ->
send left, {:left, num}
IO.puts "sent value ${num} left"
sendSidewards left, right
{:right, num} ->
send right, {:right, num}
IO.puts "sent value ${num} right"
sendSidewards left, right
end
end
def sendSidewards(left) do
IO.puts "Registering with left process"
send left, {:rightId, self()}
IO.puts "Awaiting connection from right process"
receive do
{:rightId, id} ->
sendSidewards(left, id)
end
end
def sendAllLeft(left, first) do
if first do send left, {:rightId, self()} end
receive do
{_, num} ->
send left, {:left, num}
IO.puts "sending left"
sendAllLeft left, :false
end
end
def makeTrack(left, remaining) do
if remaining > 0 do
IO.puts "making track #{remaining}"
nextLeft = spawn_link(sendSidewards(left))
IO.puts "made it"
makeTrack(nextLeft, remaining - 1)
else
IO.puts "making left sender"
spawn_link sendAllLeft(left, :true)
end
end
def finishLine(remaining, results, resultChan, name) do
if remaining > 0 do
receive do
{_, num} ->
finishLine(remaining-1, [num|results], resultChan, name)
end
else
send resultChan, {name, results}
end
end
def doRace(resultChan, numRunners, numThreads, name) do
IO.puts "Making tracks"
start = spawn_link makeTrack(self(), numThreads)
IO.puts "Made track"
for n <- 1..numRunners, do: send(start, n)
IO.puts "SentRunners"
finishLine(numRunners, [], resultChan, name)
end
def main() do
numThreads = 3
numRunners = 1
spawn_link doRace(self(), numRunners, numThreads, :A)
spawn_link doRace(self(), numRunners, numThreads, :B)
receive do
{:A, res} ->
IO.puts res
{:B, res} ->
IO.puts res
end
end
end
Great.main()