Advertisement
Guest User

Untitled

a guest
Oct 18th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. defmodule Servy.FourOhFourCounter do
  2.  
  3. @name __MODULE__
  4.  
  5. #Client Interface
  6.  
  7. def start(initial_state \\ %{}) do
  8. IO.puts "\nWaiting for a message"
  9. pid = spawn(@name, :listen_loop, [initial_state])
  10. Process.register pid, @name
  11. pid
  12. end
  13.  
  14. def bump_count(path) do
  15. send @name, {self(), :bump_count, path}
  16. receive do {:response, :ok} -> :ok end
  17. end
  18.  
  19.  
  20. def get_count(path) do
  21. send @name, {self(), :get_count, path}
  22. receive do {:response, count} -> count end
  23. end
  24.  
  25. def get_counts do
  26. send @name, {self(), :get_counts}
  27. receive do {:response, counts} -> counts end
  28. end
  29.  
  30. #Server Interface
  31. def listen_loop(state) do
  32. receive do
  33. {sender, :bump_count, path} ->
  34. new_state = Map.update(state, path, 1, &(&1 + 1))
  35. send sender, {:response, :ok}
  36. listen_loop(new_state)
  37. {sender, :get_count, path} ->
  38. count = Map.get(state, path, 0)
  39. send sender, {:response, count}
  40. listen_loop(state)
  41. {sender, :get_counts} ->
  42. send sender, {:response, state}
  43. listen_loop(state)
  44. unexpected ->
  45. IO.puts "Unexpected message: #{inspect unexpected}"
  46. listen_loop(state)
  47. end
  48. end
  49. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement