Advertisement
Guest User

Untitled

a guest
Aug 31st, 2016
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. %% loop.erl - Test speed of message delivery across processes.
  2. %%
  3. %% Run this with:
  4. %% timer:tc(loop, loop_test, [100, 10000]).
  5.  
  6. -module(loop).
  7.  
  8. -export([loop_test/2]).
  9.  
  10.  
  11. %% This is the main loop that each process runs.
  12. %%
  13. %% Basically just forward messages that are sent to this process to the NextPid,
  14. %% decrementing a counter.
  15. %%
  16. %% When the counter reaches 0, stop forwarding, and send `ok` to the Parent
  17. %% to notify it that we're done.
  18. %%
  19. have_fun(Parent, NextPid) ->
  20. receive
  21. {set_next, P} ->
  22. %% Change this process's `NextPid` to `P`. We'll use this message
  23. %% to close the loop when we build our cycle of processes.
  24. have_fun(Parent, P);
  25. {msg, 0} ->
  26. %% We're done!
  27. Parent ! ok,
  28. have_fun(Parent, NextPid);
  29. {msg, N} ->
  30. %% Forward this message to the next process, decrementing N.
  31. NextPid ! {msg, N - 1},
  32. have_fun(Parent, NextPid)
  33. end.
  34.  
  35.  
  36. %% Start a process.
  37. start(Parent, NextPid) ->
  38. spawn(fun () ->
  39. have_fun(Parent, NextPid)
  40. end).
  41.  
  42.  
  43. %% Build a chain of N processes.
  44. build_chain(N) ->
  45. Parent = self(),
  46. Last = start(Parent, Parent),
  47. build_chain(Parent, N - 1, {Last, Last}).
  48.  
  49. build_chain(Parent, 0, Pair) ->
  50. Pair;
  51. build_chain(Parent, N, {Head, Tail}) ->
  52. build_chain(Parent, N - 1, {start(Parent, Head), Tail}).
  53.  
  54.  
  55. loop_test(NProcs, NLaps) ->
  56. io:format("spawning processes...~n"),
  57. {First, Last} = build_chain(NProcs),
  58. %% Now close the loop by telling the last process
  59. %% to forward messages to the first.
  60. Last ! {set_next, First},
  61. io:format("starting test...~n"),
  62. First ! {msg, NLaps * NProcs},
  63. receive
  64. ok ->
  65. io:format("done!~n")
  66. end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement