Guest User

Untitled

a guest
Dec 10th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. -module(cheat_sheet_ipc).
  2.  
  3. -export([init/0, incr/1, decr/1, current/0]). % not loop/0
  4.  
  5. %% Define a constant.
  6. -define(SVC_NAME, counter_service). % atom, not Variable or string
  7.  
  8.  
  9. %% Start a new process to manage our counter.
  10. init() ->
  11. %% MyFunc is a reference to a function
  12. MyFunc = fun () -> % could all be on one line
  13. loop(0)
  14. end,
  15. %% Start a new process running MyFunc.
  16. Pid = spawn(MyFunc), % pass the function reference; don't invoke it here.
  17. %% Register the Pid, so we can send it messages by name.
  18. register(?SVC_NAME, Pid).
  19.  
  20.  
  21. %% Our message handling loop - not visible outside this module
  22. loop(Current) ->
  23. NewCurrent = receive % blocks until a new message comes in.
  24. {incr, Count} -> Current + Count; % no response
  25. {decr, Count} -> Current - Count;
  26. {current, Pid} ->
  27. Pid ! {ok, Current}, % send the response
  28. Current; % Return value so NewCurrent gets set
  29. Invalid -> % catch everything else
  30. io:format("Invalid message: ~p~n", [Invalid]),
  31. Current
  32. end,
  33. loop(NewCurrent). % tail-recurse with updated value
  34.  
  35.  
  36. %% Wrapper functions for asynchronous sends.
  37. incr(Count) -> ?SVC_NAME ! {incr, Count}.
  38. decr(Count) -> ?SVC_NAME ! {decr, Count}.
  39.  
  40. %% Wrap async send/receive as synchronous function.
  41. current() ->
  42. %% Send a message and wait for a response.
  43. ?SVC_NAME ! {current, self()},
  44. receive
  45. {ok, Current} ->
  46. io:format("Current value=~B~n", [Current])
  47. end.
Add Comment
Please, Sign In to add comment