gen_server -- newbie code critique?

Andrew Lentvorski <>
Sun May 28 13:04:11 CEST 2006


I'm trying to understand the gen_server behaviors, but I really seem to
be having some trouble.  So, what I tried to do was just create a
wrapper around a basic queue that could be accessed by multiple
processes.

It seems to do what I want, but I could certainly use some
critque at this point.

Thanks,
-a

-module(msqueue).
-behaviour(gen_server).

-define(SERVER, ?MODULE).

%% API
-export([start_link/0, start/0, in/1, out/0, stop/0]).

%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
	 terminate/2, code_change/3]).

%% API
start_link() ->
    gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).

start() ->
    gen_server:start({local, ?SERVER}, ?MODULE, [], []).


in(InObj) ->
    gen_server:call(?SERVER, {in, InObj}).

out() ->
    gen_server:call(?SERVER, {out}).

stop() ->
    gen_server:cast(?SERVER, stop).

%% gen_server callbacks
-record(state, {theQueue}).

init([]) ->
    {ok, #state{theQueue=queue:new()}}.

handle_call({in, InObj}, _From, State) ->
    QR = queue:in(InObj, State#state.theQueue),
    UpdatedState = #state{theQueue=QR},
    {reply, ok, UpdatedState};
handle_call({out}, _From, State) ->
    QR = queue:out(State#state.theQueue),
    RR = case QR of
	     {{value, Item}, QQ} ->
		 {value, Item};
	     {empty, QQ} ->
		 {empty}
	 end,
    {reply, RR, #state{theQueue=QQ}}.

handle_cast(stop, State) ->
    {stop, normal, State}.

handle_info(_Info, State) ->
    {noreply, State}.

terminate(_Reason, _State) ->
    ok.

code_change(_OldVsn, State, _Extra) ->
    {ok, State}.




More information about the erlang-questions mailing list