Last active
May 22, 2019 13:33
-
-
Save gdamjan/905ca7b9393e2b927c2b1a03e5b23046 to your computer and use it in GitHub Desktop.
This file contains 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(demo). | |
-export([main/0]). | |
%%% export these cause they are spawned: | |
-export([server_loop/2, client_loop/3]). | |
main() -> | |
{ok, Pid} = server(2), | |
client(Pid, critical, 15), | |
client(Pid, normal, 10), | |
receive | |
done -> ok | |
end. | |
server(NumClients) -> | |
ParentPid = self(), | |
Pid = spawn(?MODULE, server_loop, [ParentPid, NumClients]), | |
{ok, Pid}. | |
%%% a function can have multiple definitions (or bodies as some would say) | |
server_loop(ParentPid, 0) -> | |
ParentPid ! done; | |
server_loop(ParentPid, Counter) -> | |
%%% this simulates a slow server | |
timer:sleep(50), | |
receive | |
{critical, Timestamp, Msg} -> | |
io:fwrite("[~B] Critical message: ~p~n", [Timestamp, Msg]), | |
Counter_ = Counter | |
after 0 -> | |
receive | |
{critical, Timestamp, Msg} -> | |
io:fwrite("[~B] Critical message: ~p~n", [Timestamp, Msg]), | |
Counter_ = Counter; | |
{normal, Timestamp, Msg} -> | |
io:fwrite("[~B] Normal message: ~p~n", [Timestamp, Msg]), | |
Counter_ = Counter; | |
done -> | |
Counter_ = Counter - 1 | |
end | |
end, | |
%%% no loops in Erlang, tail recursion is priceless | |
server_loop(ParentPid, Counter_). | |
client(ServerPid, Atom, Count) -> | |
spawn(?MODULE, client_loop, [ServerPid, Atom, Count]). | |
client_loop(ServerPid, _Atom, 0) -> | |
ServerPid ! done; | |
client_loop(ServerPid, Atom, Count) -> | |
%%% not so slow client | |
timer:sleep(5), | |
Now = erlang:system_time(microsecond), | |
ServerPid ! {Atom, Now, "Hello world"}, | |
client_loop(ServerPid, Atom, Count - 1). |
Author
gdamjan
commented
May 22, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment