Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- %% loop.erl - Test speed of message delivery across processes.
- %%
- %% Run this with:
- %% timer:tc(loop, loop_test, [100, 10000]).
- -module(loop).
- -export([loop_test/2]).
- %% This is the main loop that each process runs.
- %%
- %% Basically just forward messages that are sent to this process to the NextPid,
- %% decrementing a counter.
- %%
- %% When the counter reaches 0, stop forwarding, and send `ok` to the Parent
- %% to notify it that we're done.
- %%
- have_fun(Parent, NextPid) ->
- receive
- {set_next, P} ->
- %% Change this process's `NextPid` to `P`. We'll use this message
- %% to close the loop when we build our cycle of processes.
- have_fun(Parent, P);
- {msg, 0} ->
- %% We're done!
- Parent ! ok,
- have_fun(Parent, NextPid);
- {msg, N} ->
- %% Forward this message to the next process, decrementing N.
- NextPid ! {msg, N - 1},
- have_fun(Parent, NextPid)
- end.
- %% Start a process.
- start(Parent, NextPid) ->
- spawn(fun () ->
- have_fun(Parent, NextPid)
- end).
- %% Build a chain of N processes.
- build_chain(N) ->
- Parent = self(),
- Last = start(Parent, Parent),
- build_chain(Parent, N - 1, {Last, Last}).
- build_chain(Parent, 0, Pair) ->
- Pair;
- build_chain(Parent, N, {Head, Tail}) ->
- build_chain(Parent, N - 1, {start(Parent, Head), Tail}).
- loop_test(NProcs, NLaps) ->
- io:format("spawning processes...~n"),
- {First, Last} = build_chain(NProcs),
- %% Now close the loop by telling the last process
- %% to forward messages to the first.
- Last ! {set_next, First},
- io:format("starting test...~n"),
- First ! {msg, NLaps * NProcs},
- receive
- ok ->
- io:format("done!~n")
- end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement