Skip to content

Instantly share code, notes, and snippets.

@aerosol
Created March 12, 2011 18:52
Show Gist options
  • Save aerosol/867472 to your computer and use it in GitHub Desktop.
Save aerosol/867472 to your computer and use it in GitHub Desktop.
Process ring struggle
-module(pr_ring).
-compile(export_all).
start(M, N, Message) ->
io:format("Starting ~p processes and sending ~p ~p~n", [N,M,Message]),
ProcessList = spawn_ring(M, N, []),
io:format("Spawned ~p~n", [ProcessList]),
hd(ProcessList) ! { Message, ProcessList }.
spawn_ring(_M, 0, ProcessList) ->
ProcessList;
spawn_ring(M, N, ProcessList) ->
Spawned = spawn(?MODULE, proc_loop, [M]),
spawn_ring(M, N-1, [Spawned|ProcessList] ).
proc_loop(0) ->
io:format("Done.~n"),
ok;
proc_loop(M) ->
io:format("Looping process (~p)~n", [M]),
receive
{Msg, [_|ProcessList]} ->
io:format("~p Received message ~p (~p)~n", [self(), ProcessList, M]),
io:format("Sending message from ~p to ~p~n", [self(),
hd(ProcessList)]),
hd(ProcessList) ! {Msg, lists:append(ProcessList, [self()])},
proc_loop(M-1)
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment