Created
October 25, 2013 15:52
-
-
Save stupidbodo/7156904 to your computer and use it in GitHub Desktop.
Non-blocking gen_server for erlang
This file contains 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
% non-blocking gen_server erlang | |
% By default handle_call is blocks the gen_server. | |
% Using a dispatcher-worker style, we can make | |
% handle_call non blocking | |
% The call below blocks | |
handle_call({get, Param}, From, State = #state{sock = Sock}) -> | |
Reply = do_time_consuming_remote_operation(Param, Sock), | |
{reply, Reply, State}; | |
% The call below doesnt block | |
handle_call({get, Param}, From, State = #state{sock = Sock}) -> | |
proc_lib:spawn_link(fun () -> do_time_consuming_remote_operation(Param, Sock) end), | |
{noreply, State}; | |
do_time_consuming_remote_operation(Param, Sock) -> | |
Results = do_some_work(Param, Sock), | |
gen_server:reply(From, Results). | |
% Special note on why we use annonymous function for proc_lib:spawn_link. | |
% If we dont use annonymous function, we need to call the function with | |
% a format like proc_lib:spawn_link(Module, Function, Arguments). | |
% The problem is, we dont want to export do_time_consuming_remote_operation/2 function, | |
% Thus, using an annonymous function to call do_time_consuming_remote_operation | |
% is better. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment