Created
June 6, 2016 02:49
-
-
Save samjarman/7043ac55e9518969c8c1839d670d9622 to your computer and use it in GitHub Desktop.
A simple master/worker implementation in elixir without using the built in supervisors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def master do | |
IO.puts "Beginning" | |
parent = self | |
spawn(fn -> worker(parent) end) | |
master_listener | |
end | |
def master_listener do | |
IO.puts "listening" | |
parent = self | |
receive do | |
{:fail, msg} -> IO.puts msg | |
IO.puts "re-running!" | |
spawn(fn -> worker(parent) end) | |
master_listener | |
end | |
end | |
def worker(parent) do | |
rand_num = :random.uniform(10000) | |
cond do | |
rand_num == 1 -> | |
IO.puts "Oh no, an error!" | |
IO.puts Process.alive?(parent) | |
send(parent, {:fail, "Failed"}) | |
Process.exit(self, :fail) | |
rand_num >= 2 -> | |
IO.puts "Smooth Sailing" | |
send(parent, {:succeed, "All good!"}) | |
worker(parent) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment