Created
January 30, 2013 10:29
-
-
Save odo/4672281 to your computer and use it in GitHub Desktop.
This is a demonstration of a gen_server which receives a message, does not reply but puts it into its own mailbox again so it will reply later.
This way the execution is deferred and other pending messages are processed first.
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
% This is a demonstration of a gen_server | |
% which receives a message, does not reply but | |
% puts it into its own mailbox again so it will reply later. | |
% This way the execution is deferred and other pending messages are processed first. | |
-module(msg_looper). | |
-behaviour(gen_server). | |
%% API | |
-export([start_link/0, stop/1]). | |
-export([ | |
msg/1 | |
]). | |
%% gen_server callbacks | |
-export([ | |
init/1 | |
, handle_call/3 | |
, handle_cast/2 | |
, handle_info/2 | |
, terminate/2 | |
, code_change/3]). | |
-define(SERVER, ?MODULE). | |
%%%=================================================================== | |
%%% API | |
%%%=================================================================== | |
start_link() -> | |
gen_server:start_link({local, ?SERVER}, ?MODULE, [], []). | |
stop(Pid) -> | |
gen_server:call(Pid, stop). | |
msg(Msg) -> | |
gen_server:call(?SERVER, {msg, Msg}). | |
%%%=================================================================== | |
%%% gen_server callbacks | |
%%%=================================================================== | |
init([]) -> | |
{ok, {}}. | |
handle_call({msg, Msg}, From, _State) -> | |
error_logger:info_msg("got message: ~p from ~p\n", [Msg, From]), | |
self() ! {'$gen_call', From, {msg_internal, Msg}}, | |
{noreply, {}}; | |
handle_call({msg_internal, Msg}, From, _State) -> | |
error_logger:info_msg("got internal message: ~p from ~p\n", [Msg, From]), | |
{reply, Msg, {}}. | |
handle_cast(_Msg, State) -> | |
{noreply, State}. | |
handle_info(_Info, State) -> | |
{noreply, State}. | |
terminate(_Reason, _State) -> | |
ok. | |
code_change(_OldVsn, State, _Extra) -> | |
{ok, State}. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment