Created
January 16, 2018 20:35
-
-
Save miguelsaddress/8dd8035f54653a848d0f0aa83c6794fe to your computer and use it in GitHub Desktop.
Corrected Sample code from https://code.tutsplus.com/articles/what-is-genserver-and-why-should-you-care--cms-29143
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
# code from: https://code.tutsplus.com/articles/what-is-genserver-and-why-should-you-care--cms-29143 | |
defmodule MathServer do | |
def start do | |
spawn &listen/0 | |
end | |
defp listen do | |
receive do | |
{:sqrt, caller, arg} -> send(caller, {:result, do_sqrt(arg)}) | |
_ -> IO.puts :stderr, "Not implemented." | |
end | |
listen() | |
end | |
def sqrt(server, arg) do | |
send(server, {:sqrt, self(), arg}) | |
end | |
defp do_sqrt(arg) do | |
:math.sqrt(arg) | |
end | |
def grab_result do | |
receive do | |
{:result, result} -> result | |
after 5000 -> IO.puts :stderr, "Timeout" | |
end | |
end | |
end | |
math_server = MathServer.start | |
MathServer.sqrt(math_server, 3) | |
MathServer.grab_result |> IO.puts |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment