Skip to content

Instantly share code, notes, and snippets.

@khellan
Created May 15, 2012 06:40
Show Gist options
  • Save khellan/2699609 to your computer and use it in GitHub Desktop.
Save khellan/2699609 to your computer and use it in GitHub Desktop.
Stepwise introduction to a distributed erlang message loop
-module(gobbler).
-behaviour(gen_server).
-export([code_change/3, handle_call/3, handle_cast/2, handle_info/2]).
-export([init/1, start_link/0, terminate/2]).
-export([count/0, increment/0, stop/0]).
count() -> gen_server:call(?MODULE, count).
increment() ->
gen_server:cast(?MODULE, increment).
stop() -> gen_server:cast(?MODULE, stop).
start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
code_change(_OldVsn, State, _Extra) -> {ok, State}.
handle_call(count, _From, State) -> {reply, State, State};
handle_call(_Request, _From, State) -> {reply, ignored, State}.
handle_cast(increment, State) ->
{noreply, State + 1};
handle_cast(stop, State) -> {stop, normal, State};
handle_cast(_Request, State) -> {noreply, State}.
handle_info(_Info, State) -> {noreply, State}.
init(_) -> {ok, 0}.
terminate(_Reason, State) ->
error_logger:info_msg("End result is ~p~n", [State]).
-module(loop).
-export([init/0, loop/0, ping/1, stop/1]).
init() -> spawn(loop, loop, []).
ping(Pid) -> Pid ! {ping, self()}.
stop(Pid) -> Pid ! stop.
loop() ->
receive
{ping, From} -> From ! {pong, self()};
stop -> ok
end.
-module(loop1).
-export([init/0, loop/0, ping/1, stop/1]).
init() -> spawn(loop1, loop, []).
ping(Pid) -> Pid ! {ping, self()}.
stop(Pid) -> Pid ! stop.
loop() ->
receive
{ping, From} -> From ! {pong, self()};
stop -> ok
after 1000 ->
io:format("I have decided to die~n")
end.
-module(loop2).
-export([init/0, loop/0, ping/1, stop/1]).
init() -> spawn(loop2, loop, []).
ping(Pid) -> Pid ! {ping, self()}.
stop(Pid) -> Pid ! stop.
loop() ->
receive
{ping, From} ->
From ! {pong, self()},
loop();
stop -> ok
end.
-module(loop3).
-export([init/0, loop/1, ping/1, stop/1]).
init() -> spawn(loop3, loop, [0]).
ping(Pid) -> Pid ! {ping, self()}.
stop(Pid) -> Pid ! stop.
loop(State) ->
receive
{ping, From} ->
From ! {pong, self(), State},
loop(State + 1);
stop ->
io:format("Final state = ~p~n", [State]),
ok
end.
-module(loop4).
-export([init/0, loop/1, ping/1, stop/1]).
init() ->
Pid = spawn(loop4, loop, [0]),
register(loop, Pid).
ping(Node) ->
{loop, Node} ! {ping, self()},
receive
{pong, From, State} ->
io:format("Got ~p from ~p~n", [From, State])
after 1000 -> {error, timeout}
end.
stop(Node) -> {loop, Node} ! stop.
loop(State) ->
receive
{ping, From} ->
From ! {pong, self(), State},
loop(State + 1);
stop ->
io:format("Final state = ~p~n", [State]),
ok
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment