Skip to content

Instantly share code, notes, and snippets.

@toraritte
Last active May 18, 2016 23:41
Show Gist options
  • Save toraritte/33790f32b92453c95c36fd022e3842e6 to your computer and use it in GitHub Desktop.
Save toraritte/33790f32b92453c95c36fd022e3842e6 to your computer and use it in GitHub Desktop.
Process chaining with and without a receive block
% The cause of the second output is (where the
% receive block is commented out) is that because
% the process does not expect any messages and it
% ends naturally.
%
% On the other hand, the version with receive
% expects messages (spits out any message that
% arrives) and it keeps on running until it is
% told to stop.
chain(N) ->¬
spawn_link(?MODULE,chain,[N,self()]).¬
¬
chain(0,_) ->¬
receive¬
after¬
7000 -> exit("chain ends")¬
end;¬
chain(N,Shell) ->¬
Pid = spawn_link(fun() -> chain(N-1,Shell) end),¬
Shell ! Pid,¬
io:format("~p started (~p)~n",[N-1, Pid]),
receive¬
_ -> ok¬
end.¬
¬
collect() ->¬
collect([]).¬
¬
collect(List) ->¬
receive¬
Pid -> [Pid|collect(List)]¬
after¬
0 -> List¬
end.
7> linkmon:chain(7).
6 started (<0.70.0>)
5 started (<0.71.0>)
4 started (<0.72.0>)
3 started (<0.73.0>)
2 started (<0.74.0>)
1 started (<0.75.0>)
0 started (<0.76.0>)
<0.69.0>
8> f(L),L = linkmon:collect().
[<0.70.0>,<0.71.0>,<0.72.0>,<0.73.0>,<0.74.0>,<0.75.0>,
<0.76.0>]
9> [erlang:is_process_alive(P) || P <- L ].
[true,true,true,true,true,true,true]
** exception error: "chain ends"
10> [erlang:is_process_alive(P) || P <- L ].
[false,false,false,false,false,false,false]
11>
11>
11>
chain(0,_) ->¬
receive¬
after¬
7000 -> exit("chain ends")¬
end;¬
chain(N,Shell) ->¬
Pid = spawn_link(fun() -> chain(N-1,Shell) end),¬
Shell ! Pid,¬
io:format("~p started (~p)~n",[N-1, Pid]).¬
% receive¬
% _ -> ok¬
% end.¬
11> c(linkmon).
{ok,linkmon}
12> linkmon:chain(7).
6 started (<0.88.0>)
5 started (<0.89.0>)
4 started (<0.90.0>)
3 started (<0.91.0>)
2 started (<0.92.0>)
1 started (<0.93.0>)
0 started (<0.94.0>)
<0.87.0>
13> f(L),L = linkmon:collect().
[<0.88.0>,<0.89.0>,<0.90.0>,<0.91.0>,<0.92.0>,<0.93.0>,
<0.94.0>]
14> [erlang:is_process_alive(P) || P <- L ].
[false,false,false,false,false,false,true]
15> [erlang:is_process_alive(P) || P <- L ].
[false,false,false,false,false,false,false]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment