Skip to content

Instantly share code, notes, and snippets.

@tecnowilliam
Created July 4, 2020 20:21
Show Gist options
  • Select an option

  • Save tecnowilliam/2a21c4b5105e9aaaca530469a5140d7d to your computer and use it in GitHub Desktop.

Select an option

Save tecnowilliam/2a21c4b5105e9aaaca530469a5140d7d to your computer and use it in GitHub Desktop.
% Compile: c(echo).
-module(echo).
-export([listener/0]).
-author("William Vargas").
-version("1.0").
-spec listener() -> any().
listener() ->
case rand:uniform(10) of
10 -> % It stops randomly
io:format("[echo] stopped~n");
_ ->
receive
{Pid,M} ->
io:format("[echo] ~w~n",[M]),
Pid!M,
listener();
Msg ->
io:format("[echo] ~w~n",[Msg])
end
end.
% Compile: c(super).
-module(super).
-export([super/0]).
-author("William Vargas").
-version("1.0").
-spec spawn_register(atom(),atom()) -> any().
spawn_register(Service, Function) ->
Pid = spawn_link(Service,Function,[]),
register(Service,Pid),
io:format("[supr] ~w spawned: ~w~n",[Service,Pid]),
Pid.
-spec kill(atom()) -> any().
kill(Service) ->
case is_pid(whereis(Service)) of
true ->
exit(whereis(Service),kill),
io:format("[supr] ~w killed~n",[Service]);
_ ->
ok
end.
-spec super() -> any().
super() ->
process_flag(trap_exit,true),
E = spawn_register(echo,listener),
T = spawn_register(talk,worker),
loop(E,T).
-spec loop(pid(),pid()) -> any().
loop(E,T) ->
case rand:uniform(5) of
5 -> % It stops randomly
kill(talk),
kill(echo),
io:format("[supr] stopped~n");
_ ->
receive
{'EXIT', T, _} ->
timer:sleep(1000),
loop(E,spawn_register(talk,worker));
{'EXIT', E, _} ->
timer:sleep(1000),
loop(spawn_register(echo,listener),T);
Msg ->
io:format("[supr] ~w~n",[Msg])
end
end.
% Tests:
% c(echo).
% c(talk).
% c(super).
% super:super().
% Compile: c(talk).
-module(talk).
-export([worker/0]).
-author("William Vargas").
-version("1.0").
-spec worker() -> any().
worker() ->
work(0).
-spec work(integer()) -> any().
work(N) ->
case rand:uniform(10) of
10 -> % It stops randomly
io:format("[talk] stopped~n");
_ ->
case is_pid(whereis(echo)) of
true ->
Msg = {self(),N},
echo!Msg,
io:format("[talk] ~w~n",[Msg]),
receive
_Reply ->
timer:sleep(1000),
work(N+1)
end;
_ ->
timer:sleep(1000),
io:format("[talk] retrying~n"),
work(N)
end
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment