Created
June 17, 2015 17:43
-
-
Save BernardNotarianni/57eebc51f07172b74b50 to your computer and use it in GitHub Desktop.
Broadcast over process
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module (chain). | |
-export ([new/1]). | |
-export ([send/2]). | |
-export ([stop/1]). | |
%% Create a chain of N processes | |
new (N) -> | |
[spawn (fun () -> child_reply () end) || _ <- lists: seq (1,N)]. | |
%% Send a message to all processes on chain | |
%% and wait that all of them reply | |
send (Msg, Chain) -> | |
[Pid ! {Msg, self()} || Pid <- Chain], | |
wait_for_answers (Chain). | |
%% Stop all processes of a chain | |
stop (Chain) -> | |
[Pid ! stop || Pid <- Chain], | |
ok. | |
child_reply () -> | |
receive | |
stop -> ok; | |
{Msg, Sender} -> | |
Sender ! {reply, Msg, self()}, | |
child_reply() | |
end. | |
wait_for_answers ([]) -> | |
ok; | |
wait_for_answers (Pids) -> | |
receive | |
{reply, _Msg, Pid} -> | |
case lists: member (Pid, Pids) of | |
true -> wait_for_answers (Pids -- [Pid]); | |
_ -> {error, {unknown_pid, Pid}} | |
end | |
after 1000 -> {error, timeout} | |
end. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(chain_test). | |
-include_lib ("eunit/include/eunit.hrl"). | |
broadcast_on_chain_test () -> | |
Chain = chain: new (3), | |
?assertEqual (ok, chain: send (hello, Chain)), | |
ok = chain: stop (Chain). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment