[erlang-questions] race condition while registering to gproc

ravindra pai ravindrapai34@REDACTED
Mon Sep 14 17:58:12 CEST 2015


Hi All,
          I am still learning erlang and have bulit a pub-sub system using 
cowboy websocket and gproc. While doing load testing, my code is hitting a 
race condition often, I have put the code to recover from race condition. 

I wanted to know how to avoid entering into the race condition, someone can 
have better answer :-)

Whenever new websocket connection is made to a Room,

Please see the code below.

      Check in gproc whether a gen_server representing Roomname,
      If exist subscribe to the room.
      Else spawn a gen_server and register with gproc with Roomname.
 
More often, gproc:reg({n, l, {session, Roomname}}) is raising {badmatch, 
badarg} error as you cannot register two process with {n, l, {session, 
Roomname}}.
So when a concurrent connections made to Roomname, two or more process is 
trying to do gproc:reg({n, l, {session, Roomname}}), only one process is 
succeeding.

ws_handler.erl

websocket_info({post_init, Roomname}, Req, _State) ->

    Pid = case gproc:where({n, l, {session, Roomname}}) of

        undefined ->

            % this will start a gen_server representing the room or session.

            {ok, P} = supervisor:start_child(sessions_sup, [RoomName]),

            P;

        P ->

            P

    end,

session.erl

-behaviour(gen_server).

%% @private

init([Roomname]) ->

    io:format("session init started for ~p~n", [Roomname]),

    try

        gproc:reg({n, l, {session, Roomname}}),

        gproc:reg({p, l, Roomname})

    catch

        _ -> ok

    end,

Thanks in advance for your advice,

Ravindra M
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20150914/def7afa2/attachment.htm>


More information about the erlang-questions mailing list