<div dir="ltr"><span style="font-family: arial, sans-serif; font-size: 12.8px;">Hi All,</span><div style="font-family: arial, sans-serif; font-size: 12.8px;">          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. </div><div style="font-family: arial, sans-serif; font-size: 12.8px;"><br></div><div style="font-family: arial, sans-serif; font-size: 12.8px;">I wanted to know how to avoid entering into the race condition, someone can have better answer :-)</div><div style="font-family: arial, sans-serif; font-size: 12.8px;"><br></div><div style="font-family: arial, sans-serif; font-size: 12.8px;">Whenever new websocket connection is made to a Room,</div><div style="font-family: arial, sans-serif; font-size: 12.8px;"><div><br></div><div>Please see the code below.</div></div><div style="font-family: arial, sans-serif; font-size: 12.8px;"><br></div><div style="font-family: arial, sans-serif; font-size: 12.8px;">      Check in gproc whether a gen_server representing Roomname,</div><div style="font-family: arial, sans-serif; font-size: 12.8px;">      If exist subscribe to the room.</div><div style="font-family: arial, sans-serif; font-size: 12.8px;">      Else spawn a gen_server and register with gproc with Roomname.</div><div style="font-family: arial, sans-serif; font-size: 12.8px;"> </div><div style="font-family: arial, sans-serif; font-size: 12.8px;">More often, gproc:reg({n, l, {sessi<wbr>on, Roomname}}) is raising {badmatch, badarg} error as you cannot register two process with {n, l, {session, Roomname}}.</div><div style="font-family: arial, sans-serif; font-size: 12.8px;">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.</div><div style="font-family: arial, sans-serif; font-size: 12.8px;"><br></div><div style="font-family: arial, sans-serif; font-size: 12.8px;">ws_handler.erl</div><div style="font-family: arial, sans-serif; font-size: 12.8px;"><p>websocket_info({post_init, Roomname}, Req, _State) -></p><p>    Pid = case gproc:where({n, l, {session, Roomname}}) of</p><p>        undefined -></p><p>            % this will start a gen_server representing the room or session.</p><p>            {ok, P} = supervisor:start_child(sessi<wbr>ons_sup, [RoomName]),</p><p>            P;</p><p>        P -></p><p>            P</p><p>    end,</p><p>session.erl</p><p></p><p>-behaviour(gen_server).</p><p>%% @private</p><p>init([Roomname]) -></p><p>    io:format("session init started for ~p~n", [Roomname]),</p><p>    try</p><p>        gproc:reg({n, l, {session, Roomname}}),</p><p>        gproc:reg({p, l, Roomname})</p><p>    catch</p><p>        _ -> ok</p><p></p><p>    end,</p><p>Thanks in advance for your advice,</p><p>Ravindra M</p></div></div>